Reputation: 55283
The following code sets this.statOffset
base on the existence of first and child nodes:
console.log('Node: ', this.node.childNodes.item(0))
console.log('Node length: ', this.node.childNodes.item(0).length)
this.startOffset = this.node.length - 1 ||
this.node.firstChild.length - 1 ||
this.node.childNodes.item(0).length - 1 ||
this.node.childNodes.item(0).firstChild.length - 1
It works okay. But in some cases I get an Uncaught TypeError: Cannot read property 'length' of null
in the last value: this.node.childNodes.item(0).firstChild.length - 1
Strangely, this happens when this.node.childNodes.item(0).length - 1
is the valid value. The console.logs
output:
Node: "a"
Node lenght: 1
Why is the code skipping the valid value and trying to execute the last one (which is an invalid one)?
EDIT: Structure of the nodes:
<p>
<strong>a</strong>
b
<span>
<em>c</em>
</span>
d
<strong>e</strong>
</p>
Upvotes: 0
Views: 87
Reputation: 1120
Have you tried children instead of childNodes? This can be helpful while seelcting the children, even when we try this on different browsers, children seems to work on all but childNodes doesn't work for all.
Both works differently sometimes. I've worked on IPad and I've done some work with childNodes and that wasn't working on that.
<html>
<div id="div1">
<div id="div2">
<div id="div3">
<div id="div4">
</div>
</div>
</div>
</div>
<script>
var div1 = document.getElementById("div1");
console.log(div1.childNodes.item(0).firstChild);
console.log(div1.children.item(0).firstChild)
document.getElementById("div4").innerHTML = JSON.stringify(div1.childNodes.item(0).firstChild);
document.getElementById("div4").innerHTML += div1.children.item(0).firstChild;
</script>
<html>
Upvotes: 0
Reputation: 68413
It works okay. But in some cases I get an Uncaught TypeError: Cannot read property 'length' of null in the last value: this.node.childNodes.item(0).firstChild.length - 1
Two things
childNodes
or children
rather than length since Element doesn't have length propertyAssuming that this
refers to the element on which event has happened, try
this.startOffset = this.childNodes.length ||
this.childNodes.item(0).childNodes.length;
Or by using hasChildNodes
this.startOffset = this.hasChildNodes() ||
this.childNodes.item(0).hasChildNodes();
Upvotes: 1