How to use appendChild method to add text and tags to another elements in DOM Manipulation Methods

How to use appendChild to add text and tags to another elements


<!DOCTYPE html>
<html lang="en" id="hello">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>How to use appendChild to add text and tags to another elements</title>
  <script src="main.js"></script>
</head>
<body>

<div id="outer">

      <h1 id="selector" style="border: 2px solid dodgerblue; padding : 2px"> RUSTIC TRAVEL JUNKIE</h1>

      <p id="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum ipsam blanditiis voluptatibus et, cumque expedita, quam ea! Dolorem obcaecati, fuga, culpa neque, repellat laudantium libero sed sint veritatis praesentium vitae cumque ratione eveniet optio, aspernatur ab. </p>

      <button id="inner">CLICK ME</button>

</div>
<script>


document.querySelector('#outer').addEventListener("click",function(){

var a = document.createElement("p");
//create another paragraph using createElement method
var b = document.createTextNode("Lorem ipsum dolor sit amet.");
//ADD text using createTextNode method

a.appendChild(b); //append the text into the tag p

document.getElementById('outer').appendChild(a); //append p with outer div

console.log(a);
});

</script>

</body>
</html>

Image below has 2 parts. 1st part shows the output and text before clicking the button and second image shows how text and tag got appended to outer tag on clicking the button along with console output:


Comments

Popular posts from this blog