0
How to change the content of first child or the last child using innerHTML property?
4 Antworten
+ 6
Have you even tried this?
it's just an assignment with = operator. rest of the things are already explained in question.
parentNode.firstChild.innerHTML="New Content";
+ 3
ARSHIA CHAUDHURI ,
Would have been easy to debug if you shared the code.
As I can't see the code I'll just go with my assumption.
If you have as structure like this :
```
<div id="parent">
<div>Old text 1</div>
<div>Old text 1</div>
</div>
```
firstChild will NOT retrieve <div>Old text 1</div>
But if you have :
``
<div id="parent"><div>Old text 1</div><div>Old text 1</div>
</div>
```
It'll work perfectly.
The reason first approach fails is that firstChild will return any DOM element which is first inside the #parent *even if it's an empty textNode*
So in first approach you can see there is some space after opening <div> , this space (textNode) is considered as the firstChild of #parent.
So you can either use second html markup or use `firstElementChild` instead of `firstChild`
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/firstElementChild
also using `children[0]` will give intended result.
Feel free to share your code and ask any other doubts regarding this.
+ 1
Tried the following..but still it is not showing "new text". The original html page is being shown everytime.
var a = document.getElementById("demo");
a.firstChild.innerHTML="new text" ;
0
Thank you so much