Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the text of an li element

Tags:

    <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?

like image 732
Deepak Avatar asked Mar 17 '10 08:03

Deepak


People also ask

How do I get text from an element?

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.

How do I get Li in JavaScript?

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.

How can get Li tag value in jquery?

$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });

How do I get text from Li?

If you have HTML inside the LI elements and you only want to get the text, you need innerText or textContent .


1 Answers

In your case:

document.getElementById('menu_selected').innerHTML 
like image 117
Alsciende Avatar answered Sep 21 '22 08:09

Alsciende