简体   繁体   中英

Find the number and position of elements in HTML using JavaScript

How would I, using JavaScript, find this out:

Say I have this HTML:

<element1></element1>
<element2></element2>
<element2></element2>

I would like to detect if there are 2 "element2" elements after my "element1" element. Also, they are not always next to each other.

How would I do this?

I would like to detect if there are 2 "element2" elements after my element1 element. Also, they are not always next to each other.

Assuming element1 is a div and element2 is a span ...

var element = document.getElementsByTagName('div')[0],
    spanCount = 0;

while (element = element.nextSibling) {
    if (element.tagName == 'SPAN') {
        spanCount++;
    }

    if (spanCount == 2) {
        alert('There are 2 spans following!');
        break;
    }
}

jsFiddle .

Easy with jQuery:

 $('element1').nextAll('element2').size()

See http://api.jquery.com/category/traversing/

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