Adding Text to a New Paragraph
Problem
You want to create a new paragraph with text and insert it just before the second para‐
graph within a div element:
// use getElementById to access the div element
var div = document.getElementById("target");
// use getElementsByTagName and the collection index
// to access the second paragraph
var oldPara = div.getElementsByTagName("p")[1]; // zero based index
// create a text node
var txt =
document.createTextNode("The new paragraph will contain this text");
// create a new paragraph
var para = document.createElement("p");
// append the text to the paragraph, and insert the new para
para.appendChild(txt);
div.insertBefore(para, oldPara);
EXPLAIN
The text within an element is, itself, an object within the DOM. Its type is a Text node, and it is created using a specialized method, createTextNode().The method takes one parameter: the string containing the text. shows a web page with a div element containing four paragraphs. The JavaScript creates a new paragraph from text provided by the user via a prompt.
The text could just as easily have come from a server communication or other process. The provided text is used to create a text node, which is then appended as a child node to the new paragraph. The paragraph element is inserted in the web page before the first paragraph.
Demonstrating various methods for adding content to a web page
<head>
<title>Adding Paragraphs</title>
</head>
<body>
<div id="target">
There is a language 'little known,'
Lovers claim it as their own.
<br />
Its symbols smile upon the land,
Wrought by nature's wondrous hand;
<br />
And in their silent beauty speak,
Of life and joy, to those who seek.
<br />
For Love Divine and sunny hours
In the language of the flowers.
<br />
</div>
<script>
// use getElementById to access the div element
var div = document.getElementById("target");
// get paragraph text
var txt = prompt("Enter new paragraph text","");
// use getElementsByTagName and the collection index
// to access the first paragraph
var oldPara = div.getElementsByTagName("p")[0]; //zero based index
// create a text node
var txtNode = document.createTextNode(txt);
// create a new paragraph
var para = document.createElement("p");
// append the text to the paragraph, and insert the new para
para.appendChild(txtNode);
div.insertBefore(para, oldPara);
</script>
</body>
</html>

No comments:
Post a Comment