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

Mohi
  • 1,063
  • 2
  • 16
  • 21
Deepak
  • 2,391
  • 2
  • 22
  • 28

5 Answers5

25

In your case:

document.getElementById('menu_selected').innerHTML
Alsciende
  • 25,777
  • 8
  • 48
  • 67
9

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];
}
Andy E
  • 326,646
  • 82
  • 467
  • 441
5

If you can use jQuery it boils down to

var text = $('#menu_selected').text();
Atanas Korchev
  • 30,432
  • 8
  • 57
  • 92
0

Try document.getElementById('menu_selected').text

KJ Saxena
  • 20,810
  • 24
  • 79
  • 106
0

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!

dan.riley
  • 1
  • 1