0

I have a class like below and I want to pass an element for further customization. The class should be responsible of setting up the size of the box and adds elements to it. I having hard time applying the necessary styles needed to element.

class BoxBuilder {
    constructor(element, items) {
        this.items = items;
        this.elm   = document.getElementById(element);
    }
    setSize(h, w) {
        console.log(this.elm); // returns null
        this.elm.style.width = w;
        this.elm.style.height = h;
        return this;
    }
}

And with jQuery :

class BoxBuilder {
    constructor(element, items) {
        this.items = items;
        this.elm   = $(element);
    }
    setSize(h, w) {
        console.log(this.elm); // returns [context: document, selector: "#box-container"]
        this.elm.style.width = w;
        this.elm.style.height = h;
        return this;
    }
}


// here is what I am trying to achieve
var box = new BoxBuilder('#box-container').setSize(300, 250);
Mike Cluck
  • 28,921
  • 12
  • 72
  • 85
mehany
  • 2,407
  • 2
  • 14
  • 27

3 Answers3

3

You're using a CSS selector where it's not supposed to be used. jQuery takes CSS selectors such as #box-container then strips off the # because that indicates it's an ID. To use document.getElementById just avoid using #.

So rewrite your assignment line as:

var box = new BoxBuilder('box-container').setSize(300, 250);
Mike Cluck
  • 28,921
  • 12
  • 72
  • 85
2

When you use straight JavaScript, you are getting null because you don't use the # as a part of the ID. That is an identifier for jQuery that you are looking for an element with that ID. The alternative is ., which would be by class. (Other CSS style selectors are also valid.)

So what you want to send when only using JavaScript is var box = new BoxBuilder('box-container').setSize(300, 250);

krillgar
  • 11,554
  • 6
  • 43
  • 81
1

You need to make sure that you are calling document.getElementById after the DOM is loaded. Otherwise, you won't find anything.

window.addEventListener('load', function(){
    var box = new BoxBuilder('box-container').setSize(300, 250);
});
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323