Question

Lets say i have markup like this:

    <div id="comment_box">
        <div class='comment'>
            <ul>
                <li class='comment_1'>
                    </li>
                <li class='comment_2'>
                    </li>
                <li class='comment_3'>
                    </li>
                <li class='comment_4'>
                    </li>
            </ul>
        </div>
    </div>

commentBox = $('#comment_box')

$('.comment_3', commentBox) or commentBox.find('.comment_3') or any other faster way?

Was it helpful?

Solution

Here are some points we need to keep in mind while selecting elements using JQuery:

1.Choosing Selectors

Choosing good selectors is one way to improve JavaScript's performance. A little specificity – for example, including an element type when selecting elements by class name – can go a long way. On the other hand, too much specificity can be a bad thing.

A selector such as

$('#comment_box .comment li.comment_3') is overkill,

if a selector such as

$('#comment_box li.comment_3') will get the job done.

jQuery offers many attribute-based selectors, allowing selections based on the content of arbitrary attributes using simplified regular expressions.

Wherever possible, make selections using IDs, class names, and tag names.

2.Saving Selections

jQuery doesn't cache elements for you. If you've made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.

var commentBox = $('#comment_box');

In the example above, the variable name begins with a dollar sign. Unlike in other languages, there's nothing special about the dollar sign in JavaScript – it's just another character. Here, it's used to indicate that the variable contains a jQuery object. This practice is merely convention, and is not mandatory.

Once the selection is stored in a variable, you can call jQuery methods on the variable just like you would have called them on the original selection.

A selection only fetches the elements that are on the page at the time the selection is made. If elements are added to the page later, you'll have to repeat the selection or otherwise add them to the selection stored in the variable. Stored selections don't magically update when the DOM changes.

You may refer to link http://learn.jquery.com/using-jquery-core/selecting-elements/ for more details

OTHER TIPS

Well, there are various approaches. Personally I'd go with this:

$("#comment_box .comment_3")

Typically the more specific you are the better. So for example:

$('#comment_box .comment li.comment_3')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top