问题
I have HTML document:
<div class="blog">
<div class="image"></div>
<div class="content">
<p class="text"> Some text </p>
<div class="date">23.12</div>
</div>
</div>
How can i get all elements with inner text (.text, .date), but not wrapper (.content).
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.
Need vanilla way help, without jquery.
回答1:
//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>
回答2:
You need to get container, then all children, then filter those children. If this is going into a production environment, you'll want to do some error checking and make sure none of those elements return null, undefined or some other bad value.
var container = document.querySelector('.content'),
allKids = container.querySelectorAll('*'),
kidsWithContent = Array.from(allKids).filter(item => item.textContent.length !== 0);
console.log(kidsWithContent);
<div class="blog">
<div class="image"></div>
<div class="content">
<p class="text"> Some text </p>
<div class="date">23.12</div>
<p></p>
<div></div>
</div>
</div>
回答3:
Here is another way (assuming the elements contain classes text
and date
)
var coll = document.querySelectorAll(".text, .date"); //Get HTML elements having class .text and .date
var elements = [].slice.call(coll); //Convert to array
elements.map(function(el,i) { console.log(el.innerHTML.trim()) }); //Display element innerHTML using `map` function
<div class="blog">
<div class="image"></div>
<div class="content">
<p class="text"> Some text </p>
<div class="date">23.12</div>
</div>
</div>
来源:https://stackoverflow.com/questions/46259929/select-all-html-elements-with-text