David G
David G

Reputation: 96865

What is the difference between these two ways to create an element?

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

Answers (7)

Devanshu
Devanshu

Reputation: 933

// use this

a.setAttribute("id","myDiv");

Upvotes: 0

Carlo Pires
Carlo Pires

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:

  1. create the element of type "div": document.createElement('div')
  2. set the element property "id" to "myDiv" and
  3. set "a" to "myDiv" also

Then, "a" is now "myDiv" and not the element.

Upvotes: 0

Alexandre Khoury
Alexandre Khoury

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

Jeff Watkins
Jeff Watkins

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

zzzzBov
zzzzBov

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';

Don't ever do this

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

Graham
Graham

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

Jason Hall
Jason Hall

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

Related Questions