我有两个具有定义的id的元素,它们之间有任何html,例如:
<div id='d1'>Hello</div>
<!-- Here come any html code -->
<div>Example</div><hr/><a href="">Example</a>
<div id='d2'>World</div>
是否有CSS选择器来选择#d1和#d2之间的所有元素?
答:不可以。
但是您始终可以选择JQuery:
$('#id').nextUntil('#id2')
请记住,该.nextUntil
方法选择介于两者之间的所有元素(互斥)。要选择包括两个元素的元素,请使用以下命令:
$('#id').nextUntil('#id2').andSelf().add('#id2')
<!DOCTYPE html>
<html>
<head>
<style>
.siblings * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("li.start").nextUntil("li.stop").css({"color": "red", "border": "2px solid red"});
$("li.start1").nextUntil("li.stop1").andSelf().add("li.stop1").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body>
<p>Just selecting all elements in between, exclusive.</p>
<div style="width:500px;" class="siblings">
<ul>ul (parent)
<li>li (sibling)</li>
<li>li (sibling)</li>
<li class="start">li (sibling with class name "start")</li>
<li>li (the next sibling of li with class name "start")</li>
<li>li (the next sibling of li with class name "start")</li>
<li>li (the next sibling of li with class name "start")</li>
<li class="stop">li (sibling with class name "stop")</li>
</ul>
</div>
<p>Just selecting all elements in between, inclusive.</p>
<div style="width:500px;" class="siblings">
<ul>ul (parent)
<li>li (sibling)</li>
<li>li (sibling)</li>
<li class="start1">li (sibling with class name "start")</li>
<li>li (the next sibling of li with class name "start")</li>
<li>li (the next sibling of li with class name "start")</li>
<li>li (the next sibling of li with class name "start")</li>
<li class="stop2">li (sibling with class name "stop")</li>
</ul>
</div>
</body>
</html>
我认为,这是最简单的选择。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句