Build tags in dom with builder pattern method in JavaScript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Build tags in dom with builder pattern method in JavaScript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am a novice. I want to use the builder pattern method in dom within a single div with id: container to create new tags and give the tags several attributes, but my code does not work and I do not know where the problem is. Please help me.

class createTag {
    constructor(tagName) {
        this.tagName = document.createElement(tagName);

    }
    setTagAppend(idTag, create) {
        this.position = idTag.append(create)
        return this;
    }
    setAttribute(idTag, attribute, value) {
        this.attribute = idTag.setAttribute(attribute, value);
        return this;
    }
    getAttribute(idTag, attribute) {
        this.attribute = idTag.getAttribute(attribute);
        return this;
    }
}
const newTag = new createTag('div')
    .setTagAppend(container, newTag)
    .setAttribute("calss", "color")
.color{
  background-color: red;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style/style.css">
    <title>Log In</title>
</head>

<body>
    <div id="container">
    </div>
</body>
<script src="./js/script.js">
</script>

</html>

Answer

Is this the sort of thing that you are hoping to achieve?

class createTag {
    constructor(tagName) {
        this.node = document.createElement(tagName);
    }
    setTagAppend(idTag) {
        idTag.appendChild(this.node);
        return this;
    }
    setAttribute(attribute, value) {
        this.node.setAttribute(attribute, value);
        return this;
    }
    getAttribute(idTag, attribute) {
        return this.node.hasAttribute(attribute) ? this.node.getAttribute(attribute) : false;
    }
}

const newTag = new createTag('div')
    .setTagAppend( document.getElementById('container') )
    .setAttribute( "class", "color" )
#container{
  background:yellow;
  padding:1rem;
  width:100%;
  height:100vh;
}
.color{
  width:250px;height:5rem;
  background-color: red;
}
<div id="container"></div>
We are here to answer your question about Build tags in dom with builder pattern method in JavaScript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji