Javascript 获取 li 元素的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2460706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:28:30  来源:igfitidea点击:

Get the text of an li element

javascripthtml

提问by Deepak

    <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

我想获取 id="menu-selected" 的 li 项目的文本。
现在我正在做类似的事情

   document.getElementById('menu_selected').childNodes.item(0).nodeValue

Is there any simpler way of doing the same?

有没有更简单的方法来做同样的事情?

采纳答案by Alsciende

In your case:

在你的情况下:

document.getElementById('menu_selected').innerHTML

回答by Andy E

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

如果 LI 元素中有 HTML 并且只想获取文本,则需要innerTexttextContent

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

回答by Atanas Korchev

If you can use jQuery it boils down to

如果你可以使用 jQuery,它可以归结为

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

回答by Kshitij Saxena -KJ-

Try document.getElementById('menu_selected').text

尝试 document.getElementById('menu_selected').text