简体   繁体   中英

How to get the index of an element containing specific child

I have a series of div elements, some of which contains h2 element as children (direct or indirect (descendant)). I look for a javascript or jquery to give me the index of such a div element. Moreover I want to start the search from a specific div element. I mean a div element with an index greater than x containing h2 . The following code find the ones in the series of all divs containing h2 . However, some of divs may not contain h2 and should be counted.

$(".myDivs h2:gt(2)").eq(0)

Html example:

<div class='myDivs'></div>
<div class='myDivs'><h2>Hi</h2></div>
<div class='myDivs'></div>
<div class='myDivs'><div><h2>How are you</h2></div></div>
<div class='myDivs'></div>

if x=2 I want the index of 3 for the fourth div with class myDivs containing an h2 .

This is what I found so far, which works:

$(".myDivs:gt("+x+"):has(h2)").eq(0).index()

Since gt is deprecated, the better solution is:

$(".myDivs").slice(x).has("h2").first().index()

Basically, I think you want a jquery something like this:

$(start).find("div").find("h2").parent("div").index();

From the start element, find your divs, then find the h2 tags in the divs, then get the parent divs of the h2s, and then get the index.

You may need a .each (...) after .find("h2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM