Reputation: 3611
var obj = document.createElement('div');
obj.className = 'className';
This will output the div element with class appended to it.
var obj = {
divE : function(){
return document.createElement('div')}
}
obj.divE().className = 'className';
This doesnot append the class name to the div element i.e. obj.divE()
What could be the reason? How to append class to obj.divE();
Upvotes: 0
Views: 85
Reputation: 6121
use
var ob = obj.divE();
ob.className = "className";
every time you calling obj.divE() directly it is creating a new element object.so
obj.divE().className = 'ClassName';
obj.divE().id= 'ClassName';
both lines creating different object.
You have to assign it some where to reuse.
Upvotes: 2
Reputation: 144669
The returned value of obj.divE().className = 'className';
statement is className
string. Your code creates an element, modifies it's className
property and effectively doesn't do anything. If you store the returned value:
var value = obj.divE().className = 'className';
then the stored value is 'className'
string not the created element. You have to create the element, store it and then update the className
just like your first snippet.
If you want to create a helper function you can code:
var obj = {
divE : function(cls) {
var div = document.createElement('div');
if ( cls ) {
div.className = cls;
}
return div;
}
}
var createdElement = obj.divE('className');
var anotherElement = obj.divE();
Upvotes: 3