I have HTML document:
Some text
-
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>
讨论(0)
-
//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>
讨论(0)
-
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>
讨论(0)