我正在开发Chrome扩展程序并尝试迭代网页的元素,该网页包含以下所示格式的多个实例:
<div class="wrapper">
<span class="loud" style="text-decoration: none;">...</span>
<div class="leave-gap">...</div>
<p>"Some text"</p>
<span id="id_12345" class="none">...</span>
<div class="block-footer">...</div>
<div class="leave-gap">...</div>
</div>
基本上在某些条件下,我将隐藏在第一个leave-gap
课程和block-footer
课程之间。
我建议按以下方式找到loud
类:
$('.wrapper .loud').each(function()
{
var $a = $(this);
...
假设我使用$a.next()
形式的语法来查找每个后续元素,我该如何确定元素的类?
有没有比我提出的解决方案更快的方法呢?
提前致谢。
答案 0 :(得分:4)
假设你找到了你的方式,找到元素的类,
$(element).attr("class")
或者您可以验证该课程是您想要的课程,
$(element).hasClass("className")
答案 1 :(得分:1)
您可以使用$(element).children().each(loopfunction)
来完成这项工作。
假设您要隐藏两个特定元素之间的所有内容。
检查测试用例:
$('.wrapper').each(function() {
var foundgap = false
$(this).children().each(function(){
if ($(this).hasClass('leave-gap')) {
foundgap = true; // mark the beginning of block
return;
} else if ($(this).hasClass('block-footer')) {
return false; // meet the end, break 'each' loop
} else if (foundgap) {
$(this).hide(); // I'm inside the block. do whatever you need
}
})
});
*:not(body):not(html) {
border: 1px solid blue;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="loud" style="text-decoration: none;">loud1</span>
<div class="leave-gap">leave-gap</div>
<p>"Some text"</p>
<span id="id_12345" class="none">id</span>
<div class="block-footer">fotter</div>
<div class="leave-gap">leave-gap</div>
</div>
<div class="wrapper">
<span class="loud" style="text-decoration: none;">loud2</span>
<div class="leave-gap">leave-gap</div>
<p>"Some text"</p>
<span id="id_12345" class="none">id</span>
<div class="block-footer">fotter</div>
<div class="leave-gap">leave-gap</div>
</div>
答案 2 :(得分:1)
现代Javascript中的一种可能性。
var firstLeaveGaps = document.querySelectorAll('.wrapper .leave-gap:first-of-type');
Array.prototype.forEach.call(firstLeaveGaps, function (leaveGap) {
var next = leaveGap.nextElementSibling;
while (next) {
if (next.classList.contains('block-footer')) {
break;
}
next.style.display = 'none';
next = next.nextElementSibling;
}
});
<div class="wrapper">
<span class="loud" style="text-decoration: none;">loud</span>
<div class="leave-gap">leave-gap</div>
<p>"Some text"</p>
<span id="id_12345" class="none">id</span>
<div class="block-footer">block-footer</div>
<div class="leave-gap">leave-gap</div>
</div>
<div class="wrapper">
<span class="loud" style="text-decoration: none;">loud</span>
<div class="leave-gap">leave-gap</div>
<p>"Some text"</p>
<span id="id_54321" class="none">id</span>
<div class="block-footer">block-footer<div>
<div class="leave-gap">leave-gap</div>
</div>
答案 3 :(得分:0)
您也可以使用div
隐藏class name
代码。
$(document).ready(function() {
//may be you can put the below in a function and call it when you condition meet.
$('.leave-gap').hide();
$('.block-footer').hide();
});