gpt4 book ai didi

jquery - 如何获取元素内最近的文本?

转载 作者:行者123 更新时间:2023-11-28 04:56:02 25 4
gpt4 key购买 nike

$("#item_1").text() 将返回#item_1 下的所有文本,但我只需要“第一个项目”。

是否可以使用 jquery 获取文本“第一个项目”?

<ul>    
<li id="item_1">
The First Item
<ul class="ltUndertema _khKonteringUndertemaer mt2">
<li>Item 1.1</li>
<li>Item 1.2</li>
</ul>
<li>...</li>
<li>...</li>
</ul>

最佳答案

我建议:

var text = $.trim($('#item_1').contents().filter(function(){
return this.nodeType === 3;
}).text());

JS Fiddle demo .

或者:

var text = $('#item_1').map(function(){
return $.trim(this.firstChild.nodeValue);
}).get().toString();

JS Fiddle demo .

没有 jQuery:

var text = document.querySelector('#item_1').firstChild.nodeValue.trim();

JS Fiddle demo .

引用资料:

关于jquery - 如何获取元素内最近的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23059031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com