dimButTries
dimButTries

Reputation: 878

Basic method chaining with DOM elements

I have been trying to learn how to chain methods in vanilla JS. Following simple tutorials I can add(), subtract() etc. However, going solo and trying to chain DOM elements, I am struggling with.

In the following snippet nothing is outputted, which I believe is due to this.textContent line. How do I get the getId bit?

'use strict'
let chain = {
    getId(id) {
        document.getElementById(id);
        return this;
    },
    text(content) {
        this.textContent = content;
        return this;
    }
}
window.addEventListener('load', function() {
    let dummy = chain.getId('dummy').text('works');
})
<div id='dummy'></div>

Upvotes: 2

Views: 476

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

As already explained in a comment this is not the selected element. With minimal refactoring in your code what you can do is adding a new element property to your object, setting it in getId and using that element in text. For instance:

'use strict'
let chain = {
  element: null,
  getId(id) {
    this.element = document.getElementById(id);
    return this
  },
  text(content) {
    this.element.textContent = content;
    return this;
  }
}
window.addEventListener('load', function() {
  let dummy = chain.getId('dummy').text('works');
})
<div id='dummy'></div>

Upvotes: 1

Related Questions