wyc
wyc

Reputation: 55283

Why is the following || skipping the valid value?

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

Answers (2)

Surya Purohit
Surya Purohit

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>

Fiddle

Upvotes: 0

gurvinder372
gurvinder372

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

  1. You don't need to reduce 1 from length otherwise it will only work if length is greater than 1 or 0.
  2. You need to use childNodes or children rather than length since Element doesn't have length property

Assuming 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

Related Questions