John Miller
John Miller

Reputation: 727

Find elements by class beginning with parent element

With a setup like;

var o = $('
    <div class="a a-1">
        <div class="b"></div>
        <div class="c">         
            <div class="a a-2"></div>
        </div>
        <div class="a a-3"></div>
    </div>
');

How do I find all class "a" elements?

When I try o.find('.a'), elements .a-2 and .a-3 are returned without the parent class (.a-1). So I also tried adding a wrapper '<div><div class="a a-1">...</div></div>' but since am using ajax, it messes up front-end rendering.

Any ideas?

Addendum: Someone suggested similarity to jQuery.find() ignores root node. No problem except the question requires capturing one element. In that case, .filter() should suffice. The question asks "How can I grab one..." In this case I need all of them.

Upvotes: 2

Views: 173

Answers (4)

Othmane El Kesri
Othmane El Kesri

Reputation: 603

For jQuery 1.8 and up, you can use .addBack()

o.find(".a").addBack(".a")

Prior to jQuery 1.8, use .andSelf() (now deprecated) :

o.find(".a").andSelf(".a")

Upvotes: 2

Henrik M
Henrik M

Reputation: 11

You can find your answer here:

https://stackoverflow.com/a/5332377/6199906 (copied it here..)


Here's a .find2() that'll find both root elements and children:

$.fn.find2 = function(selector) {
  return this.filter(selector).add(this.find(selector));
};

With this, you can do:

var html = '<div class="one"><div class="one"></div></div>';
var el = html.find2(".one"); // will match both divs

Here's more about it: http://danielnouri.org/notes/2011/03/14/a-jquery-find-that-also-finds-the-root-element/

Upvotes: 1

Bourbia Brahim
Bourbia Brahim

Reputation: 14712

use .andSelf() << jq 1.8 or .addBack() >>for jq 1.8 it includes also the current targeted node :

var o = $('<div class="a a-1"> <div class="b"></div><div class="c"><div class="a a-2"></div></div> <div class="a a-3"></div></div>');

console.log("number of element with andSelf .a :"+ o.find(".a").andSelf().length);
console.log("number of element with addBack .a :"+ o.find(".a").addBack().length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

DIEGO CARRASCAL
DIEGO CARRASCAL

Reputation: 2129

find looks inside the set of elements, so you could do:

var o = $('
<div class="a a-1">
    <div class="b"></div>
    <div class="c">         
        <div class="a a-2"></div>
    </div>
    <div class="a a-3"></div>
</div>
');

Then:

o = o.appendTo($('<div></div>'));

and then:

o.find('.a')...

Upvotes: 1

Related Questions