2

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?

Grateful
  • 9,685
  • 10
  • 45
  • 77

4 Answers4

1

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.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
1

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>
brk
  • 48,835
  • 10
  • 56
  • 78
0

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"
}
WebDeg Brian
  • 802
  • 1
  • 7
  • 21
0

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!';
}
mep2664
  • 104
  • 5
  • Welcome to Stack Overflow! Although this code may help to solve the problem, it doesn't explain why and/or how it answers the question. Providing this additional context would significantly improve its long-term educational value. Please edit your answer to add explanation, including what limitations and assumptions apply. – рüффп Dec 28 '17 at 09:39