[英]How to select HTML elements which don't have any attributes defined on them?
我需要使用 jQuery 來定位所有沒有屬性的 DIV 標簽,並對每個標簽應用 class。 這是一個示例 HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
所以,我需要把它變成這樣:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
如何通過 jQuery 定位沒有屬性的div
類型元素? 謝謝。
這里是 go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
現場演示: http://jsfiddle.net/phbU9/
attributes
屬性返回在元素上設置的所有屬性的列表。 “裸”元素有一個空attributes
列表。
更新:請務必閱讀下面Tim 的回答,它為舊版本的 IE 提供了解決方案,因為我自己的解決方案在 IE8 及以下版本中不起作用。
@Šime 的答案很接近,但在 IE 6、7 或 8 中不起作用,其中元素的attributes
集合具有每個可能屬性的條目,而不僅僅是 HTML 中指定的那些。 您可以通過檢查每個屬性對象的specified
屬性來解決這個問題。
現場演示: http://jsfiddle.net/timdown/6MqmK/1/
代碼:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
為了解釋 Tim Down 的回答,我建議檢查 attrs var 不是 null 特殊情況,其中 html 有評論標簽等。
您需要提供某種選擇器,在這種情況下,我使用了您的側欄,但它可以是任何東西。 然后獲取沒有 class 屬性的孩子,並添加一個新的 class。 有關示例,請參見 JSFiddle:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
因此,這將返回沒有 class 標記的 2 個元素,並使 class 的側邊欄和 div 完全不受影響。
試試 $('div:not([class])').addClass('myClass'); 這是一種通用方法,因為 class 將適用於所有沒有 class 的 div
$('#sidebar div')` or more general `$('div'); //returns collections of divs
回答這個問題:
$('#sidebar div').addClass('myClass');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.