Pregunta

Say I have this HTML:

<div id="div_box">
    <ul>
        <li class="li1"></li>
        <li class="li2"></li>
        <li class="li3"></li>
    </ul>
</div>

And I want to remove the class "li1".

I tried this with jQuery:

$("#div_box").find(".li1").removeClass("li1");

It works, but what I don't understand is why does it work. In chaining, the method only applies to the selector given. But #div_box does not have a class called "li1" so this shouldn't work.

Am I misunderstanding how chaining works? Could someone clarify on why this works?

¿Fue útil?

Solución

The .find() method return all the descendants of #div_box which is having the class li1...

not all jQuery methods return the same set of objects on which it was called upon... mostly the tree traversal methods returns a different set of objects

Otros consejos

Chaining will points to the object which is evaluated recently, In your case the recently evaluated object is the out come of .find('.li1'). If you want to add that #div_box into the selector then you have to use .addBack() in your current context.

it is well explained in the documentation... http://api.jquery.com/find/

the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The first signature for the .find()method accepts a selector expression of the same type that we can pass to the $() function. The elements will be filtered by testing whether they match this selector.

with the concern of traversing to the elements

Unlike in the rest of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top