如何获取列表项Javascript的值/文本 [英] How to get Value / Text of a List item Javascript

查看:57
本文介绍了如何获取列表项Javascript的值/文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获取<li>项目的值/文本? 我在互联网上发现了很多方法来获取下拉列表的价值. 但不是<li>项目.

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.

这是我到目前为止尝试过的:

This is what I have tried so far:

var listt = document.getElementById('content1'); 
var selectedvalue = [listt.selectedIndex].text;

推荐答案

您可以将innerText属性用于大多数浏览器,但将textContent属性用于Firefox:

You can use the innerText property for most browsers, but the textContent property for Firefox:

<ul>
    <li id="myLi">Hello, world</li>
</ul>

var li = document.getElementById("myLi")
console.log(li.textContent || li.innerText);

此处是一个演示小提琴.

如果您使用的是jQuery(您说的是,但我没有证据),它就像使用

If you are using jQuery (you say you are, but I see no evidence) it would be as simple as using the .text() function:

$("#myLi").text();

如果您的<li>也包含HTML标记,则可能需要这样做.在这种情况下,您需要使用innerHTML属性:

If your <li> contains HTML markup too, you may want that. In this case you need to use the innerHTML property:

document.getElementById("myLi").innerHTML;

同样,jQuery具有自己的等效 .html(),可满足各种不同的浏览器:

Again, jQuery has it's own equivalent .html() which caters for all sorts of different browsers:

$("#myLi").html();

这篇关于如何获取列表项Javascript的值/文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆