Why doesn't .nextElementSibling return null?

In the code below, <div>does not have a single brother and sister. previousElementSiblingreturns correctly null, but nextElementSiblingdoes not.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nextElementSibling</title>
</head>
<body>
    <div>test</div>
</body>
<script>
    var demo = document.getElementsByTagName('div')[0];
    console.log(demo.previousElementSibling);
    console.log(demo.nextElementSibling);
</script>
</html>

Console output:

enter image description here

Google Chrome Version 59.0.3071.86 (Official Build) (64-bit)

Why is this?

+4
source share
1 answer

Since Chrome is kind.

The tag <script>located in the source code is not valid, so Chrome automatically translates it to <body>where it is valid and where it becomes nextElementSibling. If you check the loaded page, you will see the following:

enter image description here

+6
source

Source: https://habr.com/ru/post/1679340/


All Articles