如何在Javascript中仅获取DOM元素中直接包含的文本? [英] How to get only directly contained text in DOM element in Javascript?

查看:19
本文介绍了如何在Javascript中仅获取DOM元素中直接包含的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div,里面有一些孩子,它直接包含如下文本:

100美元<span>一些广告</span><span>另一个广告</span>对于每个

我想在这个 DOM 元素中直接包含文本100$".

我尝试了 innerHTMLinnerTexttextContent.但它们会显示所有文本,包括如下所示的儿童文本:

const element = document.getElementById('price');console.log(element.innerText);console.log(element.innerHTML);console.log(element.textContent);

100美元<span>一些广告</span><span>另一个广告</span>对于每个

预期结果是 100$(我不需要for each"),它直接包含在父元素中的文本.这样我就可以得到价格和货币.

注意:jquery也是允许使用的.

解决方案

.clone() 克隆所选元素.

.children() 从克隆元素中选择子元素

.remove() 删除之前选择的子项

.end() 再次选择被选元素

.text() 从没有子元素的元素中获取文本

const elementText = $("#price").clone().孩子们().消除().结尾().文本();console.log(elementText.trim().split("\n")[0]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="父">家长<span>孩子 1</span><span>孩子 2</span>

<div id="价格">100美元<span>一些广告</span><span>另一个广告</span>对于每个

您也可以使用这个:

$("#price").contents().get(0).nodeValue.trim()

I have a div with some children within and its directly contained text like below:

<div id="price">
   100$
   <span>some ads</span>
   <span>another ads</span>
   for each
</div>

I want to get directly contained text '100$' in this DOM element.

I tried with innerHTML, innerText and textContent. But they show all text including children's text like below:

const element = document.getElementById('price');
console.log(element.innerText);
console.log(element.innerHTML);
console.log(element.textContent);

<div id="price">
   100$
   <span>some ads</span>
   <span>another ads</span>
   for each
</div>

The expected result is 100$(I don't need "for each") which is directly contained text in parent element. So then I can get the price and its currency.

note: jquery is also allowed to use.

解决方案

.clone() clones the selected element.

.children() selects the children from the cloned element

.remove() removes the previously selected children

.end() selects the selected element again

.text() gets the text from the element without children

const elementText = $("#price").clone()
                                .children()
                                .remove()
                                .end()
                                .text();

console.log(elementText.trim().split("\n")[0]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
  Parent
  <span>Child 1</span>
  <span>Child 2</span>
</div>

<div id="price">
   100$
   <span>some ads</span>
   <span>another ads</span>
   for each
</div>

EDIT: You can also use this:

$("#price").contents().get(0).nodeValue.trim()

这篇关于如何在Javascript中仅获取DOM元素中直接包含的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆