Home > Web Front-end > JS Tutorial > body text

How to add a paragraph in javascript

藏色散人
Release: 2023-01-07 11:41:33
Original
3630 people have browsed it

How to add a paragraph in javascript: 1. Insert an html paragraph through the "document.write" method; 2. Insert an html paragraph through the DOM method.

How to add a paragraph in javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer

How to add a paragraph in javascript?

javaScript method of inserting html paragraphs

Traditional method:

document.write method

Can be inserted directly where needed Insert


  
Copy after login

through the script tag or move it to an external function


  
...

Copy after login

, but either way will mix JavaScript code and HTML code, which is not a good practice.

innerHTML attribute

innerHTML can write html code or read html code under the selected node. Inserting through innerHTML directly replaces all the content under the selected node.

This will be overwritten.

Copy after login

DOM method

createElement方法:document.createElement(nodeName)
Copy after login

Create a new element. The following code creates a p element.

var insertElement = document.createElement("p")
appendChild方法:parent.appendChild(child)
Copy after login

Make this node a child node of the target node

var insertElement = document.createElement("p");
document.getElementById("insert").appendChild(insertElement);
creatTextNode方法:document.createTextNode(text);
Copy after login

Similar to the createElement method, but creates a text node

var txt = document.createTextNode("New insert text.");
insertElement.appendChild(txt);
insertBefore方法: parentElement.insertBefore(newElement,targetElement);
Copy after login

Insert a new element into an existing There are elements in front. Where parentElement is the parent element of the target element, newElement is the element you want to insert, and targetElement is the element you want to insert in front of it.

var newInsertElement = document.createElement("p");
insertDiv.insertBefore(newInsertElement,insertDiv);
Copy after login

Recommended study: "javascript Advanced Tutorial"

The above is the detailed content of How to add a paragraph in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!