- Element: getAttribute() method
- Syntax
- Parameters
- Return value
- Examples
- Description
- Lower casing
- Non-existing attributes
- Retrieving nonce values
- Specifications
- Browser compatibility
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- HTML DOM Element getAttribute()
- Description
- See Also:
- Tutorial:
- Syntax
- Parameters
- Return Value
- More Examples
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- .get Attribute ( )
- Как пишется
- Как понять
- How to Get and Set Attributes with Javascript
- Checking whether an Attribute Exists
- Checking whether Element has Any Attributes
- Getting the Value of an Attribute
- Getting All Attributes of the Element
- Setting the Value of an Attribute
- Removing an Attribute
Element: getAttribute() method
The getAttribute() method of the Element interface returns the value of a specified attribute on the element.
If the given attribute does not exist, the value returned will either be null or «» (the empty string); see Non-existing attributes for details.
Syntax
getAttribute(attributeName)
Parameters
Return value
A string containing the value of attributeName .
Examples
// in a console const div1 = document.getElementById("div1"); //=>Hi Champ!const exampleAttr = div1.getAttribute("id"); //=> "div1" const align = div1.getAttribute("align"); //=> null
Description
Lower casing
When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.
Non-existing attributes
All modern web browsers return null when the specified attribute does not exist on the specified element.
Retrieving nonce values
For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute(«nonce») calls are hidden.
let nonce = script.getAttribute("nonce"); // returns empty string
Instead of retrieving the nonce from the content attribute, use the nonce property:
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
HTML DOM Element getAttribute()
Get the value of the target attribute of an element:
Description
The getAttribute() method returns the value of an element’s attribute.
See Also:
Tutorial:
Syntax
Parameters
Return Value
More Examples
Get the value of the onclick attribute of a element:
Browser Support
element.getAttribute is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
.get Attribute ( )
Метод get Attribute ( ) позволяет получить значение указанного атрибута у HTML-элемента. Если атрибута нет, то метод вернёт null .
Как пишется
Скопировать ссылку «Как пишется» Скопировано
get Attribute ( ) принимает один аргумент – строку с именем атрибута. В ответ метод возвращает значение атрибута в виде строки или null , если атрибута нет на элементе.
script type="application/json" id="hydration"> script>
const scriptElement = document.querySelector('script') console.log(scriptElement.getAttribute('type'))// 'application/json'console.log(scriptElement.getAttribute('id'))// 'hydration'console.log(scriptElement.getAttribute('class'))// null
const scriptElement = document.querySelector('script') console.log(scriptElement.getAttribute('type')) // 'application/json' console.log(scriptElement.getAttribute('id')) // 'hydration' console.log(scriptElement.getAttribute('class')) // null
Как понять
Скопировать ссылку «Как понять» Скопировано
Существует множество стандартных HTML-атрибутов, и разработчики могут задавать элементу свои собственные атрибуты. Метод get Attribute ( ) является универсальным способом прочитать значение любого атрибута.
Не все атрибуты имеет смысл считывать с помощью get Attribute ( ) . Например, атрибут hidden лучше читать из поля hidden DOM-элемента, а дата-атрибуты — из поля dataset .
Сравним два варианта получения значения атрибута. Возьмём элемент и считаем его атрибуты:
Ошибка!div data-color="red" hidden>Ошибка!div>
const element = document.querySelector('div') console.log(element.hidden)// trueconsole.log(element.getAttribute('hidden'))// "" – пустая строка, т.к строкового значения у атрибута нет console.log(element.dataset.color)// "red"console.log(element.getAttribute('data-color'))// "red"
const element = document.querySelector('div') console.log(element.hidden) // true console.log(element.getAttribute('hidden')) // "" – пустая строка, т.к строкового значения у атрибута нет console.log(element.dataset.color) // "red" console.log(element.getAttribute('data-color')) // "red"
How to Get and Set Attributes with Javascript
Just like jQuery’s $.attr() method, there are native browser methods that can get and set attributes of an element.
Checking whether an Attribute Exists
The hasAttribute method can tell whether the element has the given attribute or not.
A true is returned if the element has the attribute, and false otherwise.
if(document.querySelector("#container").hasAttribute('data-post-id')) < console.log('Attribute present'); >else
Checking whether Element has Any Attributes
The hasAttributes method tells whether the element has at least one attribute present (it can be any attribute).
A true is returned if the element has any attributes present, and false if the element has no attributes at all.
if(document.querySelector("#container").hasAttributes()) < console.log('At least one attribute present'); >else
Getting the Value of an Attribute
The getAttribute method returns the value of the attribute.
var post_id = document.querySelector("#container").getAttribute('data-post-id');
If the attribute is not existing, then null or a blank value «» will be returned. There are confusions among specifications whether to return null or a blank. To be on the safer side, it is best to first check whether the attribute is existent (using hasAttribute ), and then getting its value. Otherwise a blank value may be mistaken for its value.
Getting All Attributes of the Element
The getAttributeNames method returns an array of all attribute names (values are not returned). If element has no attributes then an empty array is returned.
Once the attribute name is retrieved, its value can be found with getAttribute .
// all attributes var attributes = document.querySelector("#container").getAttributeNames(); var attribute_value; // show values of all attributes for(var i=0; i
Setting the Value of an Attribute
The setAttribute method sets the value of the attribute. If the attribute is not existing then it is added.
document.querySelector("#container").setAttribute('data-post-id', '12');
Removing an Attribute
The removeAttribute method removes the attribute from the element. If the attribute does not exist, no error is thrown.
document.querySelector("#container").removeAttribute('data-post-id');