Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
How to nest and chain my class functions with pure JS?

How can I make such code parts work? Trying to complete task with custom HTML builder - it needs to support chaining and nesting. Understand that I need to return this, but how then to output string with HTML?

// nesting
    const template = Templater().div(
     Templater().p('Hello'),
     Templater().p('World')
    )
    console.log(template.toString())
// chaining 
console.log(Templater().br('error').toString())

example of Class that I try to create:

    class Templater {
    constructor() {}
    div(tags) {
        return `<div>${tags}</div>`
    }
    span(tags) {
        return `<span>${tags}</span>`
    } 
    br(argument) {
        if(argument) {
            return new Error('Nested content is not allowed');
        } else {
            return '<br>'
        }
    } 
    p(tags) {
        return `<p>${tags}</p>`
    } 
}

Have no idea what I need to do.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Sounds like you primarily need a custom toString method that returns the state of the tags called so far.

You'll also need to change the class to a function, because classes cannot be used without new.

const templater = () => {
  let markup = '';
  const transform = tags => tags.join('');
  return {
    div(...tags) {
      markup += `<div>${transform(tags)}</div>`
      return this;
    },
    span(...tags) {
      markup += `<span>${transform(tags)}</span>`
      return this;
    },
    br(argument) {
      if (argument) {
        throw new Error('Nested content is not allowed');
      } else {
        markup += '<br>'
        return this;
      }
    },
    p(...tags) {
      markup += `<p>${transform(tags)}</p>`
      return this;
    },
    toString() {
      return markup;
    },
  };
};

// nesting
const template = templater().div(
  templater().p('Hello'),
  templater().p('World')
)
console.log(template.toString())
console.log(templater().br('error').toString())

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!