我正在尝试制作一些特殊的菜单,但我在选择最嵌套的元素(div)时遇到了问题。菜单将是动态的,因此它可以更改将div嵌套在一个div中的数量。 (父母将使用新的孩子创建)所以我需要选择最后一个(最嵌套的)而不使用更多的类od ID。 这是我直到现在写的代码:
<div id="strategy">
<div class="selected">
0
<div class="selected">
some text
<div class="selected"> this is the last div, but it can be anytime changed and more childs of this element can be created</div>
</div>
</div>
<div class="selected">
1
</div>
<div>
2
</div>
</div>
我试过的一些css:
div.selected:only-of-type {background: #F00;}
还试过nth:last-child,only-child ..我认为一切都必须有一些方法如何去做。
答案 0 :(得分:0)
如果您对jQuery开放......
$(document).ready(function() {
var $target = $('#strategy').children();
while( $target.length ) {
$target = $target.children();
}
var last = $target.end(); // You need .end() to get to the last matched set
var lastHtml = last.html();
$('body').append('<strong>deepest child is: ' + lastHtml + '</strong>');
last.css('color', 'blue');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="strategy">
<div class="selected">
0
<div class="selected">
some text
<div class="selected"> this is the last div, but it can be anytime changed and more childs of this element can be created</div>
</div>
</div>
<div class="selected">
1
</div>
<div>
2
</div>
</div>
&#13;