JavaScript获取不包括子代的textContent [英] JavaScript get textContent excluding children

查看:57
本文介绍了JavaScript获取不包括子代的textContent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我正在为JavaScript创建一个库,但不能使用jQuery.我正在尝试获取HTML元素的文本内容而没有其子元素的文本内容.

First, I'm creating a library for JavaScript and I can not use jQuery. I'm trying to get the text content of an HTML element without the text contents of its children.

innerText和textContent这两个属性都不能满足我的需要,请帮忙.

Both attributes innerText and textContent don't give me what needed, please help.

推荐答案

您可以解决将DOM API用作childNodes和nodeType.

You can solve using DOM API as childNodes and nodeType.

var elChildNode = document.querySelector("#hello").childNodes;
var sChildTextSum = "";

elChildNode.forEach(function(value){
    if(value.nodeType === Node.TEXT_NODE) { 
        console.log("Current textNode value is : ", value.nodeValue.trim());
        sChildTextSum += value.nodeValue;
    }
}); 

console.log("All text value of firstChild : ", sChildTextSum);

我如上所述创建了一个示例代码.

I created a sample code as above.

https://jsfiddle.net/nigayo/p7t9bdc3/

这篇关于JavaScript获取不包括子代的textContent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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