Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Next Sibling Element In DOM With JavaScript

Tags:

javascript

dom

How can I find the next element in the current scope? For example, I want to find div element and after this the next one which is p?

If I use document.getElementsByTagName('DIV')[0].nextSibling it returns #text. I want it to return p tag.

<div>
    <table>
        <tr>
            <td></td>
        </tr>
    </table>
</div>
<p></p>
like image 921
theChampion Avatar asked Jan 06 '15 19:01

theChampion


People also ask

What is next element sibling in JavaScript?

The Element. nextElementSibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.

How can I get previous siblings in JavaScript?

To get the previous sibling of a specific HTML Element, using JavaScript, get reference to this HTML element, and read the previousElementSibling property of this HTML Element. previousElementSibling property returns the element immediately prior to this HTML element.


1 Answers

You can use nextElementSibling. If you need to support older browsers, traverse nextSibling until you find an Element node.

like image 106
Felix Kling Avatar answered Sep 24 '22 21:09

Felix Kling