Set attribute to element in javascript

Element: setAttribute() method

Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .

Syntax

Parameters

A string specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document.

A string containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.

Boolean attributes are considered to be true if they’re present on the element at all. You should set value to the empty string ( «» ) or the attribute’s name, with no leading or trailing whitespace. See the example below for a practical demonstration.

Since the specified value gets converted into a string, specifying null doesn’t necessarily do what you expect. Instead of removing the attribute or setting its value to be null , it instead sets the attribute’s value to the string «null» . If you wish to remove an attribute, call removeAttribute() .

Return value

Exceptions

The specified attribute name contains one or more characters which are not valid in attribute names.

Examples

In the following example, setAttribute() is used to set attributes on a .

HTML

button  height: 30px; width: 100px; margin: 1em; > 

JavaScript

const button = document.querySelector("button"); button.setAttribute("name", "helloButton"); button.setAttribute("disabled", ""); 

This demonstrates two things:

  • The first call to setAttribute() above shows changing the name attribute’s value to «helloButton». You can see this using your browser’s page inspector (Chrome, Edge, Firefox, Safari).
  • To set the value of a Boolean attribute, such as disabled , you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true . The absence of the attribute means its value is false . By setting the value of the disabled attribute to the empty string ( «» ), we are setting disabled to true , which results in the button being disabled.

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

Specifications

Browser compatibility

BCD tables only load in the browser

Gecko notes

Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use Element.value instead of Element.setAttribute() .

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.

Источник

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

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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.

Источник

Set attribute to element in javascript

If I load the page from the example above, I can see that the attributes are applied to the element.

attributes applied successfully

# Create an Element with Style attribute using JavaScript

To create an element with a style attribute:

  1. Use the document.createElement() method to create the element.
  2. Use the setAttribute() method to set the style attribute on the element.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="box">div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
// ✅ Create element const el = document.createElement('div'); // ✅ Set Style Attributes on Element el.setAttribute( 'style', 'background-color: salmon; color: white; width: 150px; height: 150px;', ); // ✅ Alternatively, Set styles on Element // el.style.backgroundColor = 'salmon'; // el.style.color = 'white'; // el.style.width = '150px'; // el.style.height = '150px'; // ✅ Add text content to the element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `Hello world`; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);

We used the document.createElement method to create the element.

The only parameter we passed to the method is the type of element to be created ( div in the example).

The createElement method returns the newly created element.

We used the setAttribute method to set the style attribute on the element.

The setAttribute method takes 2 parameters:

  1. name — the name of the attribute whose value is to be set.
  2. value — the value to assign to the attribute.

If the attribute already exists, the value is updated, otherwise, a new attribute is added with the specified name and value.

Alternatively, you can use the style object to set styles on the element.

Copied!
const el = document.createElement('div'); el.style.backgroundColor = 'salmon'; el.style.color = 'white'; el.style.width = '150px'; el.style.height = '150px';

When setting styles using the style property, multi-name words are camel-cased.

You can use the textContent property to set the element’s text content or the innerHTML property to set the element’s inner HTML markup.

You shouldn’t use the innerHTML property with user-provided data without escaping it. This would leave your application open to cross-site scripting attacks.

You can use the appendChild method to add the element to the page.

The method adds a node to the end of the list of children of the element it was called on.

If I load the page from the example, I can see that the style attribute is successfully set on the element.

style attribute successfully set

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Add Attribute to DOM Element in JavaScript

The DOM is the structure of an HTML document starting from its root element till the end of the document. Any element, such as “p”, “div“, or “table“, is referred to as the DOM element. The DOM elements allow the user to modify the content of the webpage. An attribute specifies the collection of objects. Moreover, JavaScript provides setAttribute() methods for adding or modifying the attributes of DOM elements. In this post, we have demonstrated all the possible methods to add attributes to the DOM elements in JavaScript.

  • How to Add Attribute to DOM Element in JavaScript
  • Add Attribute to DOM Element
  • Add Multiple Attributes to DOM Element

How to Add Attribute to DOM Element in JavaScript?

The setAttribute() method is employed to add an attribute value to an existing element. If the attribute is already added, setAttribute() updates the value. It takes two inputs, one is the name, and the second specifies the value. By loading the webpage, the attribute property is applied to the DOM elements. The syntax of the setAttribute() method is provided below:

The parameters are described as follows:

  • name: Refers to the attribute name.
  • value: Specifies the value of the attribute.

Example 1: Add an Attribute to DOM Element

An example is considered by the addition of an attribute to the DOM element. The setAttribute() method is utilized for adding value to the attribute. The example code is written below:

< html >
< body >
< h2 >Example to add attribute to DOM element.
< p >Click the button to disable it


< button onclick = "btn_fn()" id = "btn" >Click Button

< script >
function btn_fn ( ) {
document.getElementById ( «btn» ) .setAttribute ( «disabled» , «» ) ;
}

The description of the code is provided below:

  • A button named “Click Button” is attached and has a unique id “btn”.
  • After that, this button is associated with the “btn_fn()” method.
  • In this method, “getElementById” is utilized to extract the “btn” id.
  • Finally, the “setAttribute()” method is employed to disable the button by passing an empty It disables the button by pressing it.

It is observed that after pressing the “Click button”, the disabled value is passed by the “setAttribute()” method.

Example 2: Add Multiple Attributes to DOM Element

An example is considered to add multiple attributes to the DOM element by utilizing the setAttribute() method in JavaScript. The setAttribute() method extracts the DOM elements by getElementById. After that, assign the property through the setAttribute() method. These attributes include a button, link, and styling property. For instance, the code is as follows.

< html >
< body style = "text-align: center;" >
< h2 >Example of adding an attribute using setAttribute ( ) method.
< a id = "link" >Google.com
< br > < br >
< button onclick = "fun()" >Add attribute

< script >
function fun ( ) {
document.getElementById ( «link» ) .setAttribute ( «href» , «https://www.Google.com/» ) ;
document.getElementById ( «link» ) .setAttribute ( «style» , «background-color: red;» ) ;
}

The description of the code is provided in the following order:

  • Firstly, an anchor “ ” tag is employed by passing the id “link”.
  • In this link, “com” is passed as text for display in the browser.
  • A button “Add attribute” is attached that is associated with the “fun()” method. The “func()” will be triggered by the button with the onclick value.
  • The “setAttribute()” method is utilized to fetch “link” using “getElementById” and an “href” attribute is set whose value is “https://www.google.com/”.
  • Similarly, a “style” attribute is set whose value is “background-color: red” for changing the text background color.

Firstly, the text is not clickable. After pressing the button “Add attribute”, a link is added to the text “Google.com” which is clickable now and opens the webpage associated with the link.

Conclusion

The setAttribute() method is employed for adding an attribute to the elements in JavaScript. The same method updates the value of the attribute if the DOM element already contains the attribute. This post has demonstrated the methods for adding attributes to the DOM elements in JavaScript. The setAttribtue() method takes a name and a value as arguments. Moreover, users can set multiple attributes to DOM elements by utilizing JavaScript. This article demonstrates two examples by adding as well as modifying the attribute value of the DOM element in JavaScript.

About the author

Syed Minhal Abbas

I hold a master’s degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.

Источник

Читайте также:  Html label for option
Оцените статью