Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu November 11, 2022 › #dynamically #Element

How to create a div tag using javascript

We can use the JavaScript createElement() method to create a new <div> element dynamically.

Example : create a div tag dynamically using Js. #
<script>
 const newDiv = document.createElement('div');
       newDiv.innerText = "My new div element."
       document.body.appendChild(newDiv)
</script>
Try it Yourself »
  1. In the above example, we have used the createElement() method to create a new div element and stored in a variable named newDiv.
    const newDiv = document.createElement('div');
  2. Then, we have set its value using the innerText property.
    newDiv.innerText = "My new div element."
  3. Finally, we have append the created div element to the body element as a child element.
    document.body.appendChild(newDiv)

How to set attributes to the created element. #

We can also set attributes to the created <div> element using the JavaScript property (id,class etc.). For example, if we want to include the id attribute to the created <div> element, we can use the id property. E.g. newDiv.id = "div-tag";

Example : set id attribute to the div element. #
<style>
  #div-tag{
    background-color: red;
    padding: 5px 15px;
  }
</style>
<script>
  const newDiv = document.createElement('div');
       newDiv.innerText = "My new div element."
       newDiv.id = "div-tag";
       document.body.appendChild(newDiv)
</script>

The best way to set attributes on a created element is to use the setAttribute() method.

setAttribute('id','new-id')
setAttribute('class','new-class')
setAttribute('onclick','myFunction')
Example : set id, class, onclick attributes to the div element. #
<script>
 const newDiv = document.createElement('div');
       newDiv.innerText = "My new div element."
       newDiv.setAttribute('id','new-id')
       newDiv.setAttribute('class','new-class')
       newDiv.setAttribute('onclick','myFunction()')
       document.body.appendChild(newDiv)
 
   function myFunction(){
    alert('New div element.')
   }
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All