开发者

jQuery selector helper

开发者 https://www.devze.com 2023-03-16 08:57 出处:网络
Is there a tool like Firebug, that lets you click an element on the page and it then shows you the jQuery selector for that element?

Is there a tool like Firebug, that lets you click an element on the page and it then shows you the jQuery selector for that element? These tools require you to guess the selector, and it then tells if you are right or not, but it does not help in any way to construct the selector. Firefinder->not by clicking jQuery Selecto开发者_如何学JAVArs -> not by clicking


there are many ways in which you can select an element, in fact, infinite ways. For example: <a id="a2" class="x" href="/home.php">hello</a> Can be selected by id ($("#a2")), by class ($(".x")), by type ($("a")), by href, by being a child of something, or a parent of something, or by it containing 'hello', etc.


I don't think any such tool exists, and for very good reason, there are so many ways you can select an element on a page given its tag, class, id and relationship to other elements.

Suppose we have the following:

<img src="foo.png" class="bar_1" />

We can select this the following ways:

$("img");
$("img:eq(0)");
$("img[src=foo.png]");
$("img[src^=foo]");
$("img[src$=.png]");
$("img.bar_1");
$("img.bar_1:eq(0)");
$("img[class=bar_1]");
$("img[class^=bar_]");

So on and so forth. It is for this reason no tool can tell you the selector, since there is not a single selector for any given element, but many.

That being said, you can construct a selector based on hierarchical structure. Chrome will tell you where in the DOM an element lies. Firefox will do the same via Firebug, and I believe the IEDeveloperToolbar does the same:

jQuery selector helper

In the preceding image you can see that my div#content element could be selected like this:

// I don't recommend making a habit of this
$("body.question-page > div.container > div#content").doSomething();

Of course since this element has an ID, and ID values are suppose to appear only once per page I could simplify this selector:

$("#content").doSomething();

Then again, we see once more that there are many ways to select - even when we have a guide.


Element Hiding Helper (requires Adblock Plus) does something like what you are asking for. It allows you to select an element (simple clicking won't do because sometimes you need to select the parent element) and then to choose the attributes/elements that you want to include in the selector. It then proceeds by adding the selector to Adblock Plus - but that step is optional.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号