javascript – Creating DOM elements using JS with more elements inside-ThrowExceptions

Exception or error:

I’ve got some tasks to do and I think about how to do it easier.
I have to create (using JS) div element with some class and inside this element I want to create another 2 elements (img src and button) and I’m not sure how to do it.

I can do it like:

const newElement = document.createElement('div');

after that I can add it to HTML doc and then create another elements (img src and button) and add it to the div I’ve created before but is there any faster option to create it?

How to solve:

In the same way you have created the class, you can create other two elements such as img and button and make appropriate src and textContent then using appendChild(), you can append the img and button to the newElement which is a parent div..

Then finally just append the newly created dom element to document.body like,


And the snippet as follows,

const newElement = document.createElement('div');

const image = document.createElement('img');
image.setAttribute('src', '');

const button = document.createElement('button');
button.textContent = 'Button';





Yes, you could use Template literals to build a template in a string. However, this string does not contain instances of elements are simply put; plain text. This means that to modify them, you have to parse the string into HTML.

Inserting a string into the document can be done with the Element.insertAdjacentHTML method. Don’t use innerHTML because that re-renders the HTML inside the element you append to and could break bindings with event listeners and selectors in your JavaScript.

Here’s an example of how this could work.

const getTemplate = (src) => `
  <div class="some-class">
    <img src="${src}" alt="">
    <button>Click me</button>

const template = getTemplate('');

document.body.insertAdjacentHTML('beforeend', template);

But if you are looking for best practices, then go for your original approach en consider accepting Maniraj Murugan’s answer.

Leave a Reply

Your email address will not be published. Required fields are marked *