Home >Web Front-end >JS Tutorial >How to add a paragraph in javascript

How to add a paragraph in javascript

藏色散人
藏色散人Original
2021-07-01 11:01:173838browse

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

<body>
  <script>
    document.write("<p>This is inserted.</p>");
  </script>
</body>

through the script tag or move it to an external function

<body>
  <script>
    insertParagraph("This is inserted");
  </script>
...
<script>
function insertParagraph(text){
  var str = "<p>"+text+"</p>"
  document.write(str)
}
</script>
</body>

, 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.

<div id="insert">
  <p>This will be overwritten.</p>
</div>
<script>
window.onload = function(){
  var insertDiv = document.getElementById("insert")
  alert(insertDiv.innerHTML)
  insertDiv.innerHTML = "<p>This is inserted.</p>"
}
</script>

DOM method

createElement方法:document.createElement(nodeName)

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

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

Make this node a child node of the target node

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

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);

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);

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!

Statement:
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