i2tutorials

Adding new elements dynamically in JavaScript?

 

The createElement() method in JavaScript can be used to create new items dynamically. The setAttribute() method is used to set the attributes of the newly generated element.

By clicking a button, a modal box appears and collects the required information dynamically. The collected dynamic data is displayed in the alert box and browser.

JavaScript Code:

<html>
<title>
    Adding new elements dynamically
</title>

<body>
    <button id="button">Hit me to add elements dynamically</button>
    <h3 id="heading_A"></h3>
    <h5 id="alert"></h5>
    <script>
        const button = document.getElementById('button');
        const text = document.getElementById('heading_A');
        const alrt = document.getElementById('alert');
        button.onclick = () => {
            const name = prompt('What is your name?');
            const course = prompt('Which Course we are learning ?');
            alert(`Hello ${name}, Welcome to our group...!`+ "\n" + `We are learning ${course}`);
            text.textContent = `Welcome ${name}to our group...!` + `We are learning ${course}`;
           alert(button.textContent);
           text.textContent = `Welcome ${name}to our group...!` + `We are learning ${course}`;

      }
    </script>
</body>

</html>

 

getElementById  & querySelector both are HTML DOM Elements

getElementById:

document.querySelector() method can only be used to access a single element while

document.querySelectorAll() method can be used to access all elements which match with a specified CSS selector(means group the  same class elements )

What is element and tag?

There is a subtle difference between HTML elements and HTML Tags.

HTML Tags:

HTML Tags are building blocks of HTML Page.

What HTML Tags do?

HTML Tags tell the browser how it should display content to the user.

How to write HTML Tags?

Opening tag:

<TagName>

Closing tag:

 </TagName>

 HTML Tag Example:

Adding new elements dynamically in JavaScript?

 HTML Element:

HTML Elements are components of the web page.

HTML Element includes a start tag, content, and an end tag.

Example:

<p> This is an Element</p>

You can also have attributes in your tags such as class or id name.

Example:

<p class ='className' id="IdName">This  is an element</p>

 

Exit mobile version