Grateful
Grateful

Reputation: 10175

Why can't I access `element.firstChild` in this case?

function setText() {
  // doesn't change... why not!?
  document.getElementById("demo").firstChild.innerHTML = 'changed!';
}

//calling the function with setTimeout to make sure the HTML is loaded
setTimeout(setText, 500);
<div id="demo">
  <p>first</p>
  <p>second</p>
</div>

I can't seem to be able to change <p>first</p> to <p>changed!</p>. Why not?

Upvotes: 2

Views: 1013

Answers (4)

mep2664
mep2664

Reputation: 102

Using ".firstChild" will select the whitespace in a div if there is any. In your case there is some. You have two options, either take our the whitespace/newlines or use this function instead...

function setText() {
  // doesn't change because the firstChild isn't the <p> element...
  // try using firstElementChild
  document.getElementById("demo").firstElementChild.innerHTML = 'changed!';
}

Upvotes: 0

WebDeg Brian
WebDeg Brian

Reputation: 832

You can always use children method or querySelector

function SetText(){
  document.getElementById('demo').children[0].textContent = "changed"
}

Or

function SetText() {
  document.querySelector('#demo > *').textContent = "changed"
}

Upvotes: 0

brk
brk

Reputation: 50291

On consoling document.getElementById("demo").firstChild I get this snapshot on logging document.getElementById("demo").firstChild .

The highlighted part show empty text. That may be the reason as it is not the first p element.

Instead you can use firstElementChild

function setText() {
  document.getElementById("demo").firstElementChild.innerHTML = 'changed!';
}
setTimeout(setText, 1000);
<div id="demo">
  <p>first</p>
  <p>second</p>
</div>

Upvotes: 1

jeprubio
jeprubio

Reputation: 18002

Whitespace inside elements is considered as text, and text is considered as nodes.

If you change the HTML to:

<div id="demo"><p>first</p><p>second</p></div>

it works. Try it.

Or you can use node.firstElementChild to ignore leading text, or use a library like jQuery which takes care of this.

Upvotes: 1

Related Questions