Home > Software design >  How to makes div with a paragraph button and other elements inside it in HTML/JS
How to makes div with a paragraph button and other elements inside it in HTML/JS

Time:03-27

I have a button that creates a div, that but is easy (const smth = document.createElemnt(div);), but the only problem is it is just a blank div. I would like there to be a div with a paragraph and button in it. How do I do that? This is in HTML and JS.

I have tried to do:

(document.CreateElement(“p”);
document.CreateElement(“button”))

Separately but that isn’t on the div.

CodePudding user response:

I hope you are well If I understand what you mean You want to create a div and add it to that element In JavaScript, you must first create the same div, then use appendChild to add other elements such as p and button.

const divMain = document.querySelector('#main-container')
        const div = document.createElement('div');
        const p = document.createElement('p');
        // p.classList = .....
        // p.textContent = .......
        div.appendChild(p);
        divMain.append(div);
        console.log(divMain)
<div id="main-container"></div>

Now to create the button, do exactly the same thing we did to create the p tag

CodePudding user response:

You need to append elements

let counter = 0;

document.querySelector('.container').addEventListener('click', function (event) {
  if (event.target instanceof HTMLButtonElement) {
    const div = document.createElement('div');
    const button = document.createElement('button');
    const p = document.createElement('p');
    
    button.textContent = 'Add';
    p.textContent = `${  counter} element created`;

    div.classList.add('new');
    div.append(button, p);
    
    this.append(div);
  }
});
.new {
  border: 1px solid green;
}

.new p {
  display: inline-block;
}
<div >
  <button>Add</button>
</div>

CodePudding user response:

here is answer with jquery

$(document).ready(function(){
  $("#mybtn").click(function(){
  var myhtml=`
  <p>hello world</p>
  <button>hello!</button>
  `;
    $("#mydata").html(myhtml);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="mybtn">
click me!
</button>

<div id="mydata" style="background-color: lightblue">

</div>

if you don't want to use jquery than go for jquery to javascript converters like this

  • Related