javascript - 从 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> </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 中有这样的语法。
那么如何排除那个子类呢?
提前致谢。
解决方案
您需要定位标识符(元素类/标签/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> </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>
推荐阅读
- javascript - 如何在 JavaScript 中关闭窗口时运行方法
- linux - 在使用 GCC 编译 Linux 内核时对各种 intel 处理器使用 mtune=intel
- python - 在 C 中表示字节数组的最常用方法是什么?
- node.js - 发布请求没有得到 req.body
- json - 在 Terraform 中,如何使用 for_each 并操作创建的每个资源?
- mysql - SQL:员工、经理、城市名称
- javascript - 使用 bulma 打印出一个数组
- java - 从 java 或 xml 引用 dimen.xml 值?
- powershell - PowerShell 获取最新的字符串日期
- c - 如何在 for 循环中创建具有不同名称的文件?