goetztyler goetztyler - 1 month ago 8
Javascript Question

Modifying node within object in javascript

I was a little confused about how to access the property className of a created Node object?

var track = {
mod: {
el: document.body.appendChild(document.createElement('div')),
el.className: 'w3-container w3-teal w3-hover-green'
}
};


This, unfortunately, provides the error:

Uncaught SyntaxError: Unexpected token .


I am trying to simply create an object within an object and modify properties of the internal object. I searched around and did not find anything specific to this level of access as I need the actual property of the DOM element 'className' to be modified and not just an assigned property of className.

Answer

You can use an Immediately Invoked Function Expression, like so:

 var track = {
  mod: {
    el: (function () {
      var el = document.body.appendChild(document.createElement('div'));
      el.className = 'w3-container w3-teal w3-hover-green';
      return el;
    }())
  }
};

This can be done only after body exists, ofcourse. Also, this will not refer to track or track.mod in the function.