J.dd
J.dd

Reputation: 157

Key of the object does not take -

I have an function , that creates element and set attributes according to arguments

function createInfo( x , obj , text ){
   var element = document.createElement(x);
   if( obj ){
         var obj_child = Object.keys(obj);
         for( var i = 0; i < obj_child.length; i++){
            element.setAttribute(obj_child[i], obj[obj_child[i]]);
         }
   }
   if( text )
         element.innerHTML = text;
   return element;
}

it works fine , but problem is when i pass "data-attribute" as argument , e.g

   var div =createInfo("div",{class:"left_info",data-index:index},null)

it throws

Unexpected token -

why isnt it taking - in the name of the key? Whats wrong with it?

Upvotes: 1

Views: 42

Answers (2)

jeffkmeng
jeffkmeng

Reputation: 879

Try defining the object like this:

var div =createInfo("div",{"class":"left_info","data-index":index},null)

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074008

data-index looks like "data minus index" to the JavaScript parser and doesn't make sense to it there. If you want to use it as a property name, put it in quotes, which are how you tell JavaScript that it's just a property name:

var div =createInfo("div",{class:"left_info","data-index":index},null)
// ------------------------------------------^----------^

Some older browsers may need you to put class in quotes as well, for an entirely different reason: class is a keyword. (But modern ones are fine with it not being in quotes, the JavaScript standard was updated in 2009 to understand that it's not a keyword there.)

var div =createInfo("div",{"class":"left_info","data-index":index},null)

Upvotes: 3

Related Questions