9

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()");
3

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

6 Comments

So as a general rule, if I experience the save issue I had above, it's probably a casing issue on the property itself and I need to investigate there first?
@LJM: If it's an HTML element, yes.
@LJM: Interacting with the DOM directly is the preferred way. All that you are doing with setAttribute is to add a new or change a attribute node and the browser will update the properties of the DOM element accordingly. Accessing these properties directly makes more sense.
So, as I understand it, calling setAttribute will update the underlying HTML. The browser will then refresh the DOM element. So by using setAttribute, we're actually going out of our way when we could just update the DOM directly?
@LJM: It's not updating the HTML, since this is simply text, but I think you basically understood it. The browser creates a DOM from the HTML. For each attribute of an HTML element, the browser creates a corresponding attribute node. Then the properties of the corresponding element node are initialised based on the values of its attribute nodes. If you add or change an attribute node, the browser updates the properties accordingly. Not for all attributes, but for most of them afaik. To come back to your actually question, the dot notation is just one way of accessing properties in JavaScript
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.