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
##
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]
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]
If you log text
object, you can find it is wrap.
Browser get nodes include wrap symbol.
But it can’t show in your editor
###
Solution
- for IE9 up
- 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());
- the way rplus provide
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
.