Deepak
Deepak

Reputation: 2531

Get the text of an li element

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

Upvotes: 28

Views: 79473

Answers (5)

dan.riley
dan.riley

Reputation: 1

I was wondering how to do this for a broader sense instead of selecting by ID and came across this.

const listItemTextContent = Array.from(document.querySelectorAll("li"))

const listItemTextArray = 
    listItemTextContent.map(itemText => itemText.firstChild.data)

console.log(listItemTextArray);

or you can use a condensed/chained alternative!

const listItemTextContent = 
    Array
        .from(document.querySelectorAll("li"))
        .map(itemText => itemText.firstChild.data)

console.log(listItemTextContent)

I hope this helps somebody!

Upvotes: 0

Atanas Korchev
Atanas Korchev

Reputation: 30661

If you can use jQuery it boils down to

var text = $('#menu_selected').text();

Upvotes: 6

Andy E
Andy E

Reputation: 344517

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

var liEl = document.getElementById('menu_selected');
var txt = liEl["innerText" in liEl ? "innerText" : "textContent"];

To avoid using this conditional statement every time, you could just declare a global variable:

var textContentProp = "innerText" in document.body ? "innerText" : "textContent";
function getText()
{
    return document.getElementById('menu_selected')[textContentProp];
}

Upvotes: 10

KJ Saxena
KJ Saxena

Reputation: 21828

Try document.getElementById('menu_selected').text

Upvotes: 0

Alsciende
Alsciende

Reputation: 26971

In your case:

document.getElementById('menu_selected').innerHTML

Upvotes: 26

Related Questions