Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: setAttribute() v.s. element.attribute = value to set "name" attribute

So I'm learning to manipulate the DOM and I noticed one interesting thing:

Let's say I want to set the name attribute of an element by using the "." dot notation:

element.name = "someName";
console.log(document.getElementsByName("someName")[0]); // returns "undefined"??

However if I use the document.setAttribute() method, it works fine:

element.setAttribute("name", "someName");
console.log(document.getElementsByName("someName")[0]); // returns the element like it should.

Not sure why the dot notation method doesn't work in the first case.

Why does this happen?

like image 917
dkugappi Avatar asked Dec 08 '11 05:12

dkugappi


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.

Why is setAttribute used?

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.

Which attribute is used to set the value of the element?

The value attribute in HTML is used to specify the value of the element with which it is used.

How do you change the element name in HTML?

Use the setAttribute() method to change the name attribute of an element, e.g. box. setAttribute('name', 'example-name') . The method sets or updates the value of an attribute on the specified element.


1 Answers

My guess (because you didn't specify the element type) is the element normally does not have a name attribute, so setting the DOM property like that won't work.

For example, setting the name property on an input element will work. Setting it on a div will not.

It will work, however, with setAttribute().

jsFiddle.

like image 185
alex Avatar answered Oct 12 '22 08:10

alex