Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between setAttribute and dot notation in Javascript? [duplicate]

Tags:

javascript

Possible Duplicate:
When to use setAttribute vs .attribute= in JavaScript?

Why do you sometimes set an attribute like this:

x.type = "submit"; 

and other times like this:

x.setAttribute("type", "submit");

I always figured it didn't matter which way, but I'm having an issue doing this:

x.onClick = save;

but when I switch it to this it works:

x.setAttribute("onClick", "save()");
like image 685
LJM Avatar asked Aug 09 '12 15:08

LJM


People also ask

What does setAttribute do in Javascript?

Element.setAttribute() 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.

What is the setAttribute method?

The setAttribute() method is used to set or add an attribute to a particular element and provides a value to it. If the attribute already exists, it only set or changes the value of the attribute. So, we can also use the setAttribute() method to update the existing attribute's value.

Why is setAttribute not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).

Does setAttribute overwrite?

Using setAttributeIf the attribute is already assigned to an element, the value is overwritten.


1 Answers

setAttribute only works on DOM elements and lowercases the attribute name on HTML elements. And you can't use dot notation to assign values to dynamic attribute names.

And there's also this:

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 elt.value instead of elt.setAttribute('value', val).

like image 106
Lèse majesté Avatar answered Oct 22 '22 11:10

Lèse majesté