Skip to main content

Tedshd's Dev note

JavaScript - something about childNodes and nextSibling why they get DOM is not as you imagine

Table of Contents

# JavaScript - something about childNodes and nextSibling why they get DOM is not as you imagine

childNodes MDN

nextSibling - MDN

## Sometimes we use childNodes

### HTML

<ul>
  <li>item1</li>
  <li>item2</li>
  <li>item3</li>
  <li>item4</li>
</ul>

### JavaScript

console.log(document.querySelector('ul').childNodes);
// output
[text, li, text, li, text, li, text, li, text]

螢幕快照_2015-08-29_上午12_08_56.png

Why?

Then

### HTML

<ul><li>item1</li><li>item2</li><li>item3</li><li>item4</li></ul>

### JavaScript

console.log(document.querySelector('ul').childNodes);
// output
[li, li, li, li]

螢幕快照_2015-08-29_上午12_10_07.png

If you log text object, you can find it is wrap.

螢幕快照_2015-08-29_上午12_09_30.png

Browser get nodes include wrap symbol.

But it can’t show in your editor

### Solution

  • for IE9 up

ParentNode.children

  • do a new function
Element.prototype.getChildNodes = function () {
  var array = [],
      nodes = this.childNodes;
  for(var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    if (node.nodeType === Node.ELEMENT_NODE) {
      array.push(node);
    }
  }

  return array;
};
console.log(document.querySelector('ul').getChildNodes());

HTML DOM nodeType Property

function getChildNodes(parentNode) {
  return [].filter.call(
    parentNode.childNodes,
    function(_target) {
      return _target.nodeType === Node.ELEMENT_NODE;
    });
}

## Sometimes we use nextSibling

As above

Sometimes you get text.