在 JavaScript 中操作 DOM 元素的屬性是非常頻繁的操作。本文以一段 HTML 為例,系統介紹獲取、設置與移除元素特性的三種方法,並比較它們的差異與適用場景。
以下面的 HTML 為例:
<div id="myDiv" class="bd" title="我是div">
<img id="img1" />
<a id="myA" href="https://www.baidu.com">百度</a>
</div>
var div = document.getElementById("myDiv");
var img = document.getElementById("img1");
var a = document.getElementById("myA");
//取得元素特性
alert(div.id); //"myDiv"
alert(div.className); //"bd",這裡不是 div.class,是因為 class 是保留關鍵字
alert(div.title); //"我是div"
alert(a.href); //https://www.baidu.com
//設置元素特性
div.id = "myDiv2"; //id 改為 myDiv2
div.className = "ft"; //class 改為 ft,若存在名為 ft 的樣式,會立刻變為該樣式
div.title = "我是myDiv2";
div.align = "center"; //設置居中對齊
img.src = "images/img1.gif";
a.innerHTML = "新浪"; //百度 改為 新浪
a.href = "https://www.sina.com.cn";
這組方法分別用於獲取、設置與移除元素特性。getAttribute() 接受特性名作為參數;setAttribute() 接受特性名和特性值兩個參數;removeAttribute() 接受要移除的特性名。
var div = document.getElementById("myDiv");
//取得元素特性
alert(div.getAttribute("id")); //"myDiv"
alert(div.getAttribute("class")); //"bd",注意這裡是 class 而非 className
alert(div.getAttribute("title"));
//設置元素特性
div.setAttribute("id","myDiv2");
div.setAttribute("class","ft"); //這裡同樣是 class,而不是 className
div.setAttribute("align","center");
//移除元素特性
div.removeAttribute("class"); //移除 class 特性
需要注意的是,這組方法在早期 IE6、7 中存在異常,removeAttribute() 在 IE6 中甚至不支援,因此不推荐廣泛使用,但在設置自定義特性時可以考慮。
var div = document.getElementById("myDiv");
//取得元素特性
alert(div.attributes["id"].nodeValue); //"myDiv"
//設置元素特性
div.attributes["id"].nodeValue = "myDiv2";
//移除元素特性
div.attributes.removeNamedItem("class"); //移除 class 特性
三種方法各有側重:直接透過物件屬性操作最為直觀常用,但要注意 class 需用 className(因為 class 是保留字);getAttribute/setAttribute 系列在處理自定義特性時更靈活;而 attributes 屬性則提供了另一種基於節點的操作視角。實際開發中,可根據需求與相容性考量靈活選用。