- HTML DOM Element setAttribute()
- See Also:
- Tutorial:
- Syntax
- Parameters
- Return Value
- Note
- NO:
- YES:
- More Examples
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Element.setAttribute()
- Синтаксис
- Пример
- Примечания
- Спецификация
- Found a content problem with this page?
- Setattribute function in javascript
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- SetAttribute JavaScript
- Examples of SetAttribute JavaScript
- Example #1
- Example #2
- Example #3
- Example #4
- Example #5
- Conclusion
- Recommended Articles
HTML DOM Element setAttribute()
The setAttribute() method sets a new value to an attribute.
If the attribute does not exist, it is created first.
See Also:
Tutorial:
Syntax
Parameters
Parameter | Description |
name | Required. The name of the attribute. |
value | Required. The new attribute value. |
Return Value
Note
It is possible to add a style attribute with a value to an element, but it is not recommended because it can overwrite other properties in the style attribute.
NO:
YES:
More Examples
Change an input field to an input button:
Add a href attribute to an element:
Change the value of the target attribute to «_self»:
Browser Support
element.setAttribute() 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.
Element.setAttribute()
Добавляет новый атрибут или изменяет значение существующего атрибута у выбранного элемента.
Синтаксис
element.setAttribute(name, value);
Пример
В следующем примере, setAttribute() используется, чтобы установить атрибут disabled кнопки , делая её отключённой.
var b = document.querySelector("button"); b.setAttribute("disabled", "disabled");
Примечания
При вызове на элементе внутри HTML документа, setAttribute переведёт имя атрибута в нижний регистр.
Если указанный атрибут уже существует, его значение изменится на новое. Если атрибута ранее не существовало, он будет создан.
Несмотря на то, что метод getAttribute() возвращает null у удалённых атрибутов, вы должны использовать removeAttribute() (en-US) вместо elt.setAttribute(attr, null), чтобы удалить атрибут. Последний заставит значение null быть строкой «null» , которая, вероятно, не то, что вы хотите.
Использование setAttribute() для изменения определённых атрибутов особенно значимо в XUL, так как работает непоследовательно, а атрибут определяет значение по умолчанию. Для того, чтобы получить или изменить текущие значения, вы должны использовать свойства. Например, elt.value вместо elt.setAttribure(‘value’, val).
Чтобы установить атрибут, которому значение не нужно, такой как, например, атрибут autoplay элемента , используйте null или пустое значение. Например: elt.setAttribute(‘autoplay’, »)
Методы DOM имеют дело с атрибутами элементов:
Не знают пространства имён, наиболее часто используемые методы | Вариант, знающий пространство имён (Уровень DOM 2) | Уровень DOM 1 методы для работы с Attr узлами напрямую (используется редко) | Уровень DOM 2 знает о методах пространства имён для работы с Attr узлами напрямую (используется редко) |
---|---|---|---|
setAttribute (DOM 1) | setAttributeNS (en-US) | setAttributeNode (en-US) | setAttributeNodeNS (en-US) |
getAttribute (DOM 1) | getAttributeNS (en-US) | getAttributeNode (en-US) | getAttributeNodeNS (en-US) |
hasAttribute (DOM 2) | hasAttributeNS (en-US) | — | — |
removeAttribute (DOM 1) | removeAttributeNS (en-US) | removeAttributeNode (en-US) | — |
Спецификация
Found a content problem with this page?
This page was last modified on 21 июн. 2023 г. by MDN contributors.
Setattribute function in javascript
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
SetAttribute JavaScript
In this article, you will learn how to set Attributes from HTML elements in JavaScript. This method setAttribute is used to add specific attributes to an element by giving the attribute a certain value. If the specific attribute is already present/ assigned, the value in it will be updated or overwritten else new attribute is added with specified value and name. Also, it is the DOMString that specifies the name of the attribute whose value has to be set. DOM is an API for HTML and XML documents that define the logical structure of documents. In this topic, we are going to learn about the SetAttribute JavaScript.
Web development, programming languages, Software testing & others
The attribute name is converted to lower-case automatically when setAttribute() is used on an HTML element, any value except the string is converted to string automatically.
Element.setAttribute(name, value);
Parameters name specifies the name of the value whose value is to be set and value specifies the value which is to be assigned to the attribute.
Since, the specified value gets converted to a string, specifying ‘null’ value sets’s attribute value to string ‘null’ whose return value will be ‘undefined’.
*setAttribute() javascript method does not return any value.
Examples of SetAttribute JavaScript
Let us see few examples on how to use setAttribute()
Example #1
function sample ()
After clicking on the Click Here button the output will be as shown below.
This example shows how an input field can be modified to an input button. HTML elements define all javascript properties to standard HTML attributes hence while trying to set the attributes to non-standard attributes, the user needs to use javascript setAttribute() function.
Example #2
A Link: Go to Google.com Click the button to set the href attribute with a value of "www.google.com" of the element id
Here, after clicking on Try it, link google.com is the href attribute set to value and now looks like a link.
Example #3
Hi eduCBA!
Example #4
function fun_color()
On clicking on the button, the background color would change to yellow as specified in setAttribute()
Let me explain the above example,
- Id, onclick, and style are the attributes.
- When the button gets clicked, javascript function fun_color is called.
- In the function, we are getting the item using ‘document.getElementById(“button”)’
- Then we are adding to attribute value style and background color as yellow
- Since the attribute is present, the value will change to yellow.
Let us now see what happens if the attribute is not present, considering the above example.
function fun_color()
Since there is no attribute style “ background”, the button shows the default background color.
On clicking on the button, the background color would change to yellow as specified in setAttribute().
Example #5
function fun_btn()
We can see that the button has been disabled.
- Call to setAttribute() , sets to disabled. An empty string or name of the attribute are recommended values
- If the attribute is present, regardless of its actual value, value is considered to be true else false
- On setting attribute value to ‘disabled’ to “ “ empty string, disabled is set to tue which automatically results in button to be disabled.
We shouldn’t use javascript setAttribute() for styling, to change or add styles, we can access style object.
We shouldn’t set style attributes like the below
element.setAttribute("style", "background-color: yellow;");
Instead, we need to use element.style.backgroundColor = “yellow”;
Let us look at an example,
In scripts.js
var element = document.getElementById('sample'); element.style.color = "violet"; element.style.backgroundColor = "yellow";
Conclusion
setAttribute() method is used only while dealing with DOM i.e Document Object Model as it uses literal text. We have also noticed that the string name is case insensitive and does not return any value. We also have getAttribute() and removeAttribute() which are used to get the current value of an attribute and to remove an attribute respectively.
Recommended Articles
This is a guide to SetAttribute JavaScript. Here we discuss the examples on how to use setAttribute() in JavaScript along with the outputs. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVASCRIPT Course Bundle — 83 Courses in 1 | 18 Mock Tests
343+ Hours of HD Videos
83 Courses
18 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5