previousSibling and nextSibling returns text?

前端 未结 1 1622
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 02:53

Could someone clarify why the code below returns #text instead of \'li\' ?

Shouldn\'t the next sibling of first li be li ? Similarly previous sibling of last li be

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 03:07

    The whitespace between the two is also a node. That's why JS libraries exist. To give you options like retrieving element siblings.

    If the HTML source looked like this:

    It would work as you expect it, because there's no whitespace between the li elements.

    More recently, two more properties have been introduced, called previousElementSibling and nextElementSibling, which ignore that whitespace. It works from IE9 and up, with the other major browsers supporting it for a while now.

    0 讨论(0)
提交回复
热议问题