Published: 09 Oct 2018 › Updated: 09 Oct 2018

JavaScript学习笔记:jQuery内容选择器的原生实现
深入学习jQuery选择器系列第五篇——过滤选择器之内容选择器
jQuery 很好用,但如果只是偶尔用到,那么引入这么大一个库恐怕就得不偿失了。何况学习的时候,总是要搞明白各种实现方法的。偏偏网上大多数试图实现 no jQuery 的教程都浅尝辄止,没有涉及到内容选择器等没有对应 CSS 选择器的语法。在自己摸索出 :contains 的原生实现后,查到了这篇博文——写得很好,我决定用 ES6 语法重写一下。
$('span:contains("test")').css('color','red')
const spans = document.getElementsByTagName('span');
for (const span of spans) {
if(span.textContent.includes('text')) {
span.style.color = 'red';
}
}
原作者已经提供了详细的过程,我就不重复了,总之思路就是用循环语句获取全部元素再来判断。
Leave JavaScript学习笔记:jQuery内容选择器的原生实现 to:
Read more #javascript posts
Best Posts From ivysrono
We have not curated any of ivysrono's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.