list 如何获取列表项 Javascript 的值/文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18185963/
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
How to get Value / Text of a List item Javascript
提问by Erdem Güng?r
how can i get the Value / Text of a <li>
item ?
I found on the internet much ways to get the value for a dropdown list.
But not for a <li>
item.
如何获取项目的值/文本<li>
?我在互联网上找到了很多获取下拉列表值的方法。但不是一个<li>
项目。
This is what I have tried so far:
这是我迄今为止尝试过的:
var listt = document.getElementById('content1');
var selectedvalue = [listt.selectedIndex].text;
回答by CodingIntrigue
You can use the innerText
property for most browsers, but the textContent
property for Firefox:
innerText
大多数浏览器都可以使用该属性,但textContent
Firefox的属性:
<ul>
<li id="myLi">Hello, world</li>
</ul>
var li = document.getElementById("myLi")
console.log(li.textContent || li.innerText);
Hereis a fiddle to demonstrate.
这里有一个小提琴来演示。
If you are using jQuery (you say you are, but I see no evidence) it would be as simple as using the .text()function:
如果你正在使用 jQuery(你说你是,但我看不到任何证据),它就像使用.text()函数一样简单:
$("#myLi").text();
If your <li>
contains HTML markup too, you may want that. In this case you need to use the innerHTML
property:
如果您也<li>
包含 HTML 标记,您可能需要它。在这种情况下,您需要使用该innerHTML
属性:
document.getElementById("myLi").innerHTML;
Again, jQuery has it's own equivalent .html()which caters for all sorts of different browsers:
同样,jQuery 有它自己的等效.html(),它迎合了各种不同的浏览器:
$("#myLi").html();
回答by Anthony Grist
Assuming myLi
is a reference to the <li>
element you want to get the text of, it's as simple as:
假设myLi
是对<li>
要获取其文本的元素的引用,它很简单:
myLi.innerText
Note that <li>
elements don't have values, because they're not inputs. They have content which can be a string of text or HTML defining other page elements. If your <li>
element contained other elements, and you wanted the HTML of those as a string, you could instead do:
请注意,<li>
元素没有值,因为它们不是输入。它们的内容可以是定义其他页面元素的文本字符串或 HTML。如果您的<li>
元素包含其他元素,并且您希望将这些元素的 HTML 作为字符串,则可以改为:
myLi.innerHTML
What's the difference? Let's assume your HTML looked like this:
有什么不同?假设您的 HTML 如下所示:
<li><span>Some text</span></li>
Then
然后
console.log(myLi.innerHTML); // outputs: <span>Some text</span>
console.log(myLi.innerText); // outputs: Some text
回答by Ninthony
I would just use innerHTML if your list item has an ID or class name and assuming there is no other html in your list item.
如果您的列表项具有 ID 或类名并且假设您的列表项中没有其他 html,我将只使用 innerHTML。
<ul>
<li class="list-item">Item1</li>
<li class="list-item">Item2</li>
<li class="list-item">Item3</li>
</ul>
<script>
var list = document.getElementsByClassName('list-item');
var listArray=[];
for (var i=0;i<list.length;i++){
listArray.push(list[i].innerHTML);
console.log(listArray[i]);
}
</script>
//output
Item1
Item2
Item3