Javascript DOM Paragraph append

Description

Javascript DOM Paragraph append

View in separate window

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Adding Paragraphs</title>
<script type="text/javascript">
//<![CDATA[//from w  w w.j a v  a2s.com

window.onload=function() {

   // use getElementById to access the div element
   let div = document.getElementById("target");

   // get paragraph text
   let txt = prompt("Enter new paragraph text","");

   // use getElementsByTagName and the collection index to access the first paragraph
   let oldPara = div.getElementsByTagName("p")[0]; // zero based index

   // create a text node
   let txtNode = document.createTextNode(txt);

   // create a new paragraph
   let para = document.createElement("p");

   // append the text to the paragraph, and insert the new para
   para.appendChild(txtNode);

   div.insertBefore(para, oldPara);

  }
//]]>
</script>
</head>
<body>
<div id="target">
  <p>CSS<br />CSS</p>
  <p>HTML<br />HTML</p>
  <p>Java<br />Java</p>
  <p>Javascript<br />Javascript
  </p>
</div>
</body>
</html>



PreviousNext

Related