Select all HTML elements with text

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-17 07:13:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!