Whats the difference between nextElementSibling vs nextSibling

前端 未结 2 1674
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 05:36

Although I seem to get strange results occasionally these seem to me to be the same so can someone describe the difference?

2条回答
  •  情深已故
    2020-12-05 06:06

    'nextSibling' returns the next Node object whereas 'nextElementSibling' returns the next Element object, so probably the real question is what is the difference between a Node & an Element?

    Basically an Element is specified by an HTML Tag whereas a Node is any Object in the DOM, so an Element is a Node but a Node can also include Text Nodes in the form of whitespace, comments, text characters or line breaks. For more info on Elements vs Nodes see this Difference between Node object and Element object?

    i.e Take the following DOM snippet

    Me

    Hi

    Using nextSibling you would get:

    console.log(document.getElementById('start').nextSibling); // "\nMe\n"
    console.log(document.getElementById('start').nextSibling.nextSibling); // "

    Whereas using nextElementSibling you would get:

    console.log(document.getElementById('start').nextElementSibling);// "

    "

    Also nextElementSibling is IE10+, being the newer method whereas nextSibling has full browser support

提交回复
热议问题