<ul class="leftbutton" > <li id="menu-selected">Sample 1</li> <li>Sample 2</li> <li>Sample 3</li> <li>Sample 4</li> <li>Sample 5</li> </ul>
I want to get the text of the li item which the id="menu-selected".
Right now I am doing something like
document.getElementById('menu_selected').childNodes.item(0).nodeValue
Is there any simpler way of doing the same?
Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.
To get all li elements in an array with JavaScript, we can call the getElementsByTagName method to get all the li elements. Then we can use the spread operator to spread all the items in the node list to an array. to call document. getElementById("navbar") to get the div element.
$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });
If you have HTML inside the LI elements and you only want to get the text, you need innerText or textContent .
In your case:
document.getElementById('menu_selected').innerHTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With