![](/img/trans.png)
[英]How can I get the text inside an element P excluding their possible child elements A with javascript DOM?
[英]JavaScript - How to get the text of the first child of a DOM element?
我试图在JavaScript中构建一个水果数组,并且这样做,我需要获取ul
元素的所有li
子元素的文本值。 我取得了一些不错的进步,因为我能够找到列表中的孩子人数。
$("#fruits-list > li").length
=> 6
我也可以按索引查找元素。 在这里,我找到了第一个使用此元素的元素
$("#fruits-list > li")[0]
=> <li id="apple">Apple</li>
我可以获取该元素,但是无法获取该元素的测试值。 在这里,我试图获取文本值apple
,而我几乎尝试了所有东西。 我试过了
$("#fruits-list > li")[0].text
$("#fruits-list > li")[0].html
$("#fruits-list > li")[0].val
我得到undefined
为他们三个。 我还尝试了在所有方法的末尾添加()
,但遇到TypeError: Is not a function
。
我在这里找不到答案。 任何帮助表示赞赏。 提前致谢。
当将括号符号与jQuery元素上的索引一起使用时,您将获得一个DOM元素。 这些对象不能直接用jQuery函数调用。 请改用eq 。
采用
$("#fruits-list > li").eq(0).text()
请注意,如果最终目标是建立LI元素文本的数组,则只需
var arr = $("#fruits-list > li").map(function(){ return $(this).text() }).get();
text
, html
和val
不是DOM的属性,它们是jQuery方法。
您可以简单地执行自然的JS方法。
document.querySelector("#fruits-list > li").textContent; //or innerText for legacy IE
querySelector
返回元素列表的第一项。 (但是,如果您使用jQuery,我建议dystroy的答案)
当您访问$("#fruits-list > li")[0]
,您将获得一个HTMLElement
对象,这就是为什么您不能在其上使用jQuery函数的原因。 dystroy的解决方案让您使用jQuery获取文本,因为eq
返回jQuery的实例。 你也可以
$("#fruits-list > li")[0].textContent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.