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

Reza Heidari
  • 1,192
  • 2
  • 18
  • 23
Deepak
  • 2,481
  • 2
  • 23
  • 28

5 Answers5

25

In your case:

document.getElementById('menu_selected').innerHTML
Alsciende
  • 26,583
  • 9
  • 51
  • 67
10

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
  • 338,112
  • 86
  • 474
  • 445
6

If you can use jQuery it boils down to

var text = $('#menu_selected').text();
Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93
0

Try document.getElementById('menu_selected').text

KJ Saxena
  • 21,452
  • 24
  • 81
  • 109
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