选择所有带有文本的HTML元素 [英] Select all HTML elements with text
本文介绍了选择所有带有文本的HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有HTML文档:
<div class="blog">
<div class="image"></div>
<div class="content">
<p class="text"> Some text </p>
<div class="date">23.12</div>
</div>
</div>
如何获取所有带有内部文本(.text,.date)而不是包装器(.content)的元素.
How can i get all elements with inner text (.text, .date), but not wrapper (.content).
这只是一个例子,在实际情况下,我不知道真正的HTML结构,但是我需要一种方法来选择所有带有文本的元素,除了包装元素.
It's just an example, in real situation i don't know real HTML structure, but i need a method how select all elements with text, except their wrappers.
需要香草方式的帮助,无需使用jQuery.
Need vanilla way help, without jquery.
推荐答案
//first select the container
var container = document.body,
//then all nodes
elems = container.getElementsByTagName("*"),
len = elems.length,
elem,
elemText,
i,
//we assign unnecessary elements
unwanted = ["script", "images", "imput"];
//a normal loop
for(i=0;i<len;i+=1){
elem = elems[i];
//pay attention here
//if the element does not have children it means that it will only contain text
if(unwanted.indexOf(elem.nodeName.toLowerCase())=="-1"){
if(!elem.children.length){
//you also have to check that the text exists
elemText = elem.innerText;
if(elemText){
//and finally
console.log(elem, elemText);
}
}
}
}
<div class="blog">
<div class="image"></div>
<div class="content">
<p class="text"> Some text </p>
<div class="date">23.12</div>
</div>
</div>
这篇关于选择所有带有文本的HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文