假设我的 HTML 看起来可能是以下两种方式之一:
选项 1:
<h2>My header
<span class="apple">My Span</span>
</h2>
选项 2:
<h2>My header</h2>
通过 jAuery,我想将一个跨度附加到嵌套跨度(如果存在)或直接附加到标题,从而产生以下结果之一:
选项 1:
<h2>My header
<span class="apple">My Span
<span>My Span Inserted via jQuery</span>
</span>
</h2>
选项 2:
<h2>My header
<span>My Span Inserted via jQuery</span>
</h2>
是否有一个聪明的选择器可以检测上述两种情况?当然,我可以首先检查我的 header 是否有一个包含“apple”类的跨度。如果是,就这样做,否则,就那样做。不过,我想知道是否有更优雅、更简洁的解决方案。
最佳答案
以下选择器选择所有 <h2>
没有<span>
元素或 <span>
具有 <h2>
的元素作为家长。
$("h2:not(:has(span)), h2 > span")
.append("<span>My Span Inserted via jQuery</span>");
关于jQuery 选择器确定 'or' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1689624/