开发者

Get the text of an li element

开发者 https://www.devze.com 2022-12-22 23:53 出处:网络
<ul class="leftbutton" > <li id="menu-selected">Sample 1</li> <li>Sample 2</li>
<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 ite开发者_如何学Pythonm 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?


In your case:

document.getElementById('menu_selected').innerHTML


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];
}


If you can use jQuery it boils down to

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


Try document.getElementById('menu_selected').text


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消