开发者

Is there a tool to help me understand DOM traversal in jQuery?

I think I have a basic understanding of DOM traversal, but I doubt I'm doing it efficiently.

For example:

<textarea name="description"></textarea>
<p class="notes"><small>100 characters or less <span class="remainder"></span></small></p>

I have a keyup event listener on the textarea. I want the .remainder span to display something like "(50 characters remaining)" as the user types in the textarea.

I am currently accessing the .remainder span like this:

var remainder = $('textarea').next('p').children('small').children('.remainder');

I assume there is a simpler way to do this - maybe through selectors? I am hoping to find some kind of tool, like WebKi开发者_开发百科t's Developer Tools, to visually show me how one element relates to another.

Can anyone tell me if such a thing exists? Any advice you may have on DOM traversal would be much appreciated too.

Thanks!


You can try using Firebug for Firefox. This plugin gives you access the the DOM and you can execute code right in the console and see the effect immediately.

For example, After you install Firebug, open it and choose the console tab. Then in the right hand window type your Javascript code including your jQuery selectors etc and click run.


I'd recommend you study CSS selectors a little more. As you can see from the other comments there are other ways to get to that element in a faster way. As a rule of thumb, CSS selectors are faster than JS function calls, so try to minimize the calls unless necessary.

As for the tool you asked about, Firebug rules, as others mentioned. You have a built-in console where you can call functions from the current web page, so there no need to press refresh after every test. It also displays all the data you need in a nice, comprehensive way. Also, when building your CSS queries, you may use the HTML tab to study the document structure and decide what selectors to use.

Chrome also has a developer console filling in the same role, and it also exists firebug Lite, and this one does not require a specific browser(it's written in JS only).


The simpler way to do that would be to use .find() instead of .children().

$('textarea').next('p').find('.remainder')


If there is only one element with class remainder you can do:

var remainder = $(".remainder")

... to select it. If there are more, then you will have to narrow down your search. And Firebug is what I recommend as well.


Firebug for Firefox is a very handy tool. Also, I suggest you using Developer Tools that comes within Chrome. You can see the resources in the page, write scripts and test them on the fly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜