选择包含文本的所有HTML元素

时间:2017-09-17 01:41:34

标签: javascript html ecmascript-6

我有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,。日期)的所有元素,而不是包装器(.content)。

这只是一个例子,在实际情况下我不知道真正的HTML结构,但我需要一个方法如何选择所有带文本的元素,除了它们的包装器。

需要vanilla way帮助,没有jquery。

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
//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);
      }
    }
  }
}
&#13;
<div class="blog">
  <div class="image"></div>
  <div class="content">
    <p class="text"> Some text </p>
    <div class="date">23.12</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你需要获得容器,然后是所有孩子,然后过滤那些孩子。如果这是进入生产环境,您将要进行一些错误检查,并确保这些元素都不会返回null,undefined或其他一些错误的值。

&#13;
&#13;
var container = document.querySelector('.content'),
    allKids = container.querySelectorAll('*'),
    kidsWithContent = Array.from(allKids).filter(item => item.textContent.length !== 0);
    
console.log(kidsWithContent);
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是另一种方式(假设元素包含类textdate

&#13;
&#13;
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
&#13;
<div class="blog">
    <div class="image"></div>
    <div class="content">
        <p class="text"> Some text </p>
        <div class="date">23.12</div>
    </div>
</div>
&#13;
&#13;
&#13;