首页 > 解决方案 > 从 getElementsByClassName 中排除子类

问题描述

一个网页有这样的结构,我想要一个叫做“post-entry”的类的所有文本内容,除了它下面的一个子类。我已将不需要的文本标记为“排除此”:

<div class="post-entry">
    <p><em></em></p>
    <p><em>INCLUDE THIS</em></p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p><em></em></p>
    <blockquote></blockquote>
    <h4></h4>
    <p><em></em></p>
    <p>&nbsp;</p>

    <span class="scroll-top">
        <a href="#scroll-top" title="Go to top"><span class="dashicons dashicons-arrow-up-alt2 top"></span>EXCLUDE THIS</a>
    </span>
</div>

我一直在使用下面的代码来获取我想要的数据,它工作正常,除了它包含我在前面的示例中标记为“EXCLUDE THIS”的部分。

var contentElem = document.getElementById('content');
var titleText = contentElem.getElementsByClassName('entry-title');
var entryText = contentElem.getElementsByClassName('post-entry');

var textToLog = titleText[0].innerText + "\n\n" + entryText[0].innerText; 
console.log(textToLog);

我搜索的一些解决方案在实施或类似的情况下返回“无法读取未定义的属性'innerText'” 。要么我的语法不正确,要么测试的解决方案不适合该任务。我很确定在没有 jQuery 的 javascript 中有这样的语法。

那么如何排除那个子类呢?

提前致谢。

标签: javascripthtmlgetelementsbyclassname

解决方案


您需要定位标识符(元素类/标签/id)并明确排除它。在您上面的代码中,标识符将是scroll-top

// post-entry element
var postEntry = document.getElementsByClassName('post-entry')[0];

// get 1st level (direct) children under post-entry div
var postEntryChildren = postEntry.childNodes;

var content = '';
for(var i =0;i<postEntryChildren.length;i++){
  // check if the textContent is not empty and the className is not 'scroll-top' which includes the text to be excluded
  if(postEntryChildren[i].textContent && postEntryChildren[i].textContent.trim() && postEntryChildren[i].className !== 'scroll-top'){
    if(content) content += '\n';
    content += postEntryChildren[i].textContent
  }
}

console.log(content);
<div class="post-entry">
    <p><em></em></p>
    <p><em>INCLUDE THIS</em></p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p>INCLUDE THIS</p>
    <p><em></em></p>
    <blockquote></blockquote>
    <h4></h4>
    <p><em></em></p>
    <p>&nbsp;</p>

    <span class="scroll-top">
        <a href="#scroll-top" title="Go to top"><span class="dashicons dashicons-arrow-up-alt2 top"></span>EXCLUDE THIS</a>
    </span>
</div>


推荐阅读