JAVA SCRIPT - Inserting a New Paragraph - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Inserting a New Paragraph - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, December 29, 2018

JAVA SCRIPT - Inserting a New Paragraph

 Inserting a New Paragraph



Problem

You want to insert a new paragraph just before the third paragraph within a div element. 

Solution

Use some method to access the third paragraph, such as getElementsByTagName(), to get all of the paragraphs for a div element. Then use the createElement() and insert Before() DOM methods to add the new paragraph just before the existing third paragraph:


// get the target div
var div = document.getElementById("target");
// retrieve a collection of paragraphs
var paras = div.getElementsByTagName("p");
// if a third para exists, insert the new element before
// otherwise, append the paragraph to the end of the div
var newPara = document.createElement("p");
if (paras[3]) {
 div.insertBefore(newPara, paras[3]);
} else {
 div.appendChild(newPara);
}


EXPLAIN 

The document.createElement() method creates any HTML element, which then can be inserted or appended into the page. In the solution, the new paragraph element is inserted before an existing paragraph using insertBefore().

Because we’re interested in inserting the new paragraph before the existing third para‐ graph, we need to retrieve a collection of the div element’s paragraphs, check to make sure a third paragraph exists, and then use insertBefore() to insert the new paragraph before the existing one.

If the third paragraph doesn’t exist, we can append the element to the end of the div element using appendChild().


No comments:

Post a Comment

Post Top Ad