+ 4

JS question...

Hi guys, I created two unordered list, one display A,B,C and other display D,E,F. I am learning JS, as you can see, I want to change 'A' to 'haha' but it doesn't work. What should I do? I think firstChild and lastChild property seems cannot use to me, but other people use it as well? <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <header> <ul id='myList1'> <li>A</li> <li>B</li> <li>C</li> </ul> <ul id='myList2'> <li>D</li> <li>E</li> <li>F</li> </ul> <p id='test'></p> </header> <script> var ul1 = document.getElementById('myList1'); var first1 = ul1.firstChild; first1.innerHTML = 'haha'; </script> </body> </html>

17th Dec 2017, 1:28 PM
kelvin hong ę–¹
kelvin hong ę–¹ - avatar
4 Answers
+ 12
check the below read this and other sites for more info https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children https://www.w3schools.com/jsref/prop_element_children.asp <header> <ul id='myList1'> <li>A</li> <li>B</li> <li>C</li> </ul> <ul id='myList2'> <li>D</li> <li>E</li> <li>F</li> </ul> <p id='test'></p> </header> <script> var ul1 = document.getElementById('myList1').children //need children after your selection // var first1 = ul1.firstChild; // this line not necessary ul1[0].innerText = 'haha'; //target 1st child element </script> </body>
17th Dec 2017, 1:39 PM
Lord Krishna
Lord Krishna - avatar
+ 4
So I have to add children and the selection. Thanks, it was helpful!
17th Dec 2017, 1:54 PM
kelvin hong ę–¹
kelvin hong ę–¹ - avatar
+ 2
Sorry there, I found that the solution is a few page after that. Using replaceChild, because this replace a node by a node, but not replace the content of the node. This also states that DOM is more emphasize on the node but no the content inside them.
17th Dec 2017, 1:37 PM
kelvin hong ę–¹
kelvin hong ę–¹ - avatar
+ 2
You may add an id to the <li> element and then edit the innerHTML property of this element!
17th Dec 2017, 2:44 PM
Naveen Maurya
Naveen Maurya - avatar