Add attribute to element in javascript

How to add/update an attribute to an HTML element using JavaScript?

I’m trying to find a way that will add / update attribute using JavaScript. I know I can do it with setAttribute() function but that doesn’t work in IE.

4 Answers 4

You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn’t work, then maybe element.attributeName = ‘value’ might work.

this works. it creates attribute if it doesn’t exists and updates it if it does exist. is this documented somewhere as far as how this works?

When I do the following: document.getElementById(«nav»).setAttribute(«class», «active»); it works in the Chrome JS console, but in the actual page it doesn’t work..any ideas? By the way, in the actual page I include the .js file before the end of the body scope.

What seems easy is actually tricky if you want to be completely compatible.

var e = document.createElement('div');

Let’s say you have an id of ‘div1’ to add.

e['id'] = 'div1'; e.id = 'div1'; e.attributes['id'] = 'div1'; e.createAttribute('id','div1')

These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP’s default with no updates).

Читайте также:  Lab3 Anketa

But there are contingencies, of course. Will not work in IE prior to 8: e.attributes[‘style’] Will not error but won’t actually set the class, it must be className: e[‘class’] .
However, if you’re using attributes then this WILL work: e.attributes[‘class’]

In summary, think of attributes as literal and object-oriented.

In literal, you just want it to spit out x=’y’ and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE’s style exception). But because these are really objects things can get confused.

Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = ‘fooClass’ and e.id = ‘fooID’. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.

It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it’s style.width not style=»width:50px». Also remember tagName but this is already set by createElement so you shouldn’t need to worry about it.

This was longer than I wanted, but CSS manipulation in JS is tricky business.

Источник

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 custom attribute using JavaScript

I am using The DynaTree (https://code.google.com/p/dynatree) but I am having some problems and hoping someone can help.. I am displaying the tree on the page like below:

However I am trying to change the icon on a item no matter if it’s selected or not only using JavaScript. the new icon I want to use is base2.gif I have tried using the following but it don’t seem to work:

document.getElementById('item1').data = "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'"; 

3 Answers 3

Use the setAttribute method:

document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'"); 

But you really should be using data followed with a dash and with its property, like:

And to do it in JS use the dataset property:

document.getElementById('item1').dataset.icon = "base.gif"; 

The dataset property might be useful if only browsers compliant with HTML5 are considered, but that is a short list and wider support is required for the general web. I’d stick to using setAttribute for now.

still can’t get it to work by using document.getElementById(‘item1’).setAttribute(‘data’, «icon: ‘base2.gif’, url: ‘output.htm’, target: ‘AccessPage’, output: ‘1’»);

I have added the code and added a alert at the end (so it will alart when the code is done), and I can also see the icon not changing. (when I remove the code is see my alart display, so i know there is somthing wrong with the code I just added.)

var article = document.querySelector('#electriccars'), data = article.dataset; // data.columns -> "3" // data.indexnumber -> "12314" // data.parent -> "cars" 

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif"; 

For people coming from Google, this question is not about data attributes — OP added a non-standard attribute to their HTML object, and wondered how to set it.

However, you should not add custom attributes to your properties — you should use data attributes — e.g. OP should have used data-icon , data-url , data-target , etc.

In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:

ele.setAttribute(attributeName, value); 

to change the given attribute attributeName to value for the DOM element ele .

document.getElementById("someElement").setAttribute("data-id", 2); 

Note that you can also use .dataset to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute method instead.

Источник

Оцените статью