Search code examples
javascripthtmlcssdomdom-manipulation

Changing css styling dynamically using javascript


I'm practicing javascript. Here I'm creating a JS class for dynamically creating web elements such as div, a, etc. The following code shows a class for creating a div element:

class DivBlock {

 //creates the div element
 constructor(id) {
   this.ele = document.createElement('div');
   this.ele.id = id;
   this.ele.style.height = '100px';
   this.ele.style.width = '200px';
   this.ele.style.border = '1px solid black';
 }

 // sets the css properties
 css(props) {
   var keyslist = Object.keys(props);
   console.log(keyslist);
   console.log(props);
   var style = keyslist.map((keys) => {
     this.ele.style.keys = props[keys];
     return this.ele.style.keys;
   });
   console.log(style);
 }

 getId() {
   return this.ele.id;
 }

 getNode() {
   return this.ele;
 }

 //adds the div-element to the parent element/tag
 mount(parent_id) {
   document.getElementById(parent_id).appendChild(this.ele);
 }

}

var d = new DivBlock('root-div');
d.mount('root') //passing parent tag id
d.css({
 height: '500px',
 backgroundColor: 'red'
});

The Html snippet:

<div id='root'> </div>

The above code is successfully creating the div but is not changing the height and background-color as mentioned by the css method. The css method should take an object having css-styling properties and its values and reflect the changes. What changes should I make in the css method or in the code to make it work?


Solution

  • Change this.ele.style.keys = props[keys]; to this.ele.style[keys] = props[keys];

    keys is variable so you need to use the bracket notation to access the prop with name that is in the variable. Otherwise you are trying to access a property of the style named literally keys.


    class DivBlock {
    
      //creates the div element
      constructor(id) {
        this.ele = document.createElement('div');
        this.ele.id = id;
        this.ele.style.height = '100px';
        this.ele.style.width = '200px';
        this.ele.style.border = '1px solid black';
      }
    
      // sets the css properties
      css(props) {
        var keyslist = Object.keys(props);
        console.log(keyslist);
        console.log(props);
        var style = keyslist.map((keys) => {
          this.ele.style[keys] = props[keys];
          return this.ele.style[keys];
        });
        console.log(style);
      }
    
      getId() {
        return this.ele.id;
      }
    
      getNode() {
        return this.ele;
      }
    
      //adds the div-element to the parent element/tag
      mount(parent_id) {
        document.getElementById(parent_id).appendChild(this.ele);
      }
    
    }
    
    var d = new DivBlock('root-div');
    d.mount('root') //passing parent tag id
    d.css({
      height: '500px',
      backgroundColor: 'red'
    });
    <div id='root'> </div>