0
How do I change the list item text using DOM (JS)? Say item3 to itemNew.
<body> <ul> <li>item1</> <li>item2</> <li>item3</> </ul> </body>
4 ответов
+ 2
You can select first ul element by it's tag name. And use lastChild property to access the lastChild of ul i.e. list with text "item3" .
var u=document.querySelector("ul");
u.lastChild.textContent="newItem";
+ 1
-set an id eg:
<li id='3'>item3</li>
-use getElementById('3') method eg:
let el = document.getElementById('3');
-Assign el to itemNew:
el = 'itemNew'
0
you should use css selectors for that
this is how to access it
let thirdListElement = document.querySelector("li:nth-child(3)").innerText;
thirdListElement = "itemNew";
0
select the targeted element using one of the method suggested and assign it to a variable (ie named 'e' or whatever you want), then to change its content, use either:
1) e.textContent or e.innerText properties to assign plain text to it
2) e.innerHTML property to assign to it html text (text parsed as html code)
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML