현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.
Summary
getAttribute()
은 해당 요소에 지정된 값을 반환 합니다. 만약 주어진 속성이 존재 하지 않는 다면, null 값이나 ""(빈문자열); 을 반환 할 것입니다. 자세한 사항은 Notes 참조 하십시오.
Syntax
var attribute = element.getAttribute(attributeName);
where
attribute
is a string containing the value ofattributeName
.attributeName
is the name of the attribute whose value you want to get.
Example
var div1 = document.getElementById("div1"); var align = div1.getAttribute("align"); alert(align); // shows the value of align for the element with id="div1"
Notes
When called on an HTML element in a DOM flagged as an HTML document, getAttribute()
lower-cases its argument before proceeding.
Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return null
when the specified attribute does not exist on the specified element and this is what the current DOM specification draft specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some DOM implementations implement this behavior. The implementation of getAttribute in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use element.hasAttribute()
to check for an attribute's existence prior to calling getAttribute()
if it is possible that the requested attribute does not exist on the specified element.
DOM methods dealing with element's attributes:
Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with Attr nodes directly (seldom used) |
DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used) |
---|---|---|---|
setAttribute (DOM 1) |
setAttributeNS |
setAttributeNode |
setAttributeNodeNS |
getAttribute (DOM 1) |
getAttributeNS |
getAttributeNode |
getAttributeNodeNS |
hasAttribute (DOM 2) |
hasAttributeNS |
- | - |
removeAttribute (DOM 1) |
removeAttributeNS |
removeAttributeNode |
- |