Reputation: 96865
var a = document.createElement('div');
a.id = "myDiv";
and
var a = document.createElement('div').id = "myDiv";
What is the difference between them such that the first one works and the second one doesn't?
Upvotes: 3
Views: 128
Reputation: 4926
In the first statement you put the created element of type "div" into variable "a", and then set the element property "id" of "a" to "myDiv". Then "a" is now the element.
In the second statement you:
Then, "a" is now "myDiv" and not the element.
Upvotes: 0
Reputation: 4032
If you really want a short way, you can write :
(window.a=document.createElement('div')).id="myDiv";
Fiddle : http://jsfiddle.net/F23cD/
Upvotes: 0
Reputation: 6357
The second one doesn't work because the "return" value from createElement is used to set the id. As that's an assignment and not chaining, it doesn't return the reference to the new element back to "a" and thus fails.
Upvotes: 2
Reputation: 179274
foo = 'bar'
as a statement actually returns a value, which is 'bar'
.
a = document.createElement('div'); //this sets `a` to DOM Node
a = document.createElement('div').id = 'myDiv'; //this sets `a` to 'myDiv'
//it's the same as
document.createElement('div').id = 'myDiv';
a = 'myDiv';
If you wanted to set both the ID and the a
variable in one line, you could use parens:
(a = document.createElement('div')).id = 'myDiv';
That's because a = document.createElement('div')
retuns the newly created DOM Node.
Upvotes: 0
Reputation: 6572
The second doesn't work as you're creating an element but immediately performing an operation upon it. The a
variable is set to the string "myDiv" instead.
Upvotes: 0
Reputation: 20930
Setting the id
of the element does not return the element. It returns "myDiv"
actually, so the var a
is getting set to "myDiv"
instead of the div itself.
Upvotes: 9