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

How to implement DOM insertion node in JS

php中世界最好的语言
Release: 2018-04-08 10:55:19
Original
2291 people have browsed it

This time I will show you how to insert nodes into DOM using JS. What are the precautions for inserting nodes into DOM using JS? The following is a practical case, let’s take a look.

The example in this article describes the DOM insertion node operation implemented by JS. Share it with everyone for your reference, the details are as follows:

1 Introduction

Inserting nodes is achieved by using the insertBefore() method.

insertBefore()The method will insert a new child node before another child node.

obj.insertBefore(new,ref)

new: Represents a new child node.
ref: Specify a node and insert a new node before this node.

Second Application

Insert a node. In this example, enter the text to be inserted in the text box on the page, and then click "Insert Before" ” button inserts text into the page.

Three complete sample codes:

<!DOCTYPE html>
<html>
<head>
<title>插入节点</title>
<script language="javascript">
 <!--
 function crNode(str)
 {
  var newP=document.createElement("p");
  var newTxt=document.createTextNode(str);
  newP.appendChild(newTxt);
  return newP;
 }
 function insetNode(nodeId,str)
 {
   var node=document.getElementById(nodeId);
   var newNode=crNode(str);
   if(node.parentNode) //判断是否拥有父节点
   node.parentNode.insertBefore(newNode,node);
 }
 -->
</script>
</head>
<body>
 <h2 id="h">在上面插入节点</h2>
 <form id="frm" name="frm">
 输入文本:<input type="text" name="txt" />
 <input type="button" value="前插入" onclick="insetNode(&#39;h&#39;,document.frm.txt.value);" />
 </form>
</body>
</html>
Copy after login

I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of mint-ui usage in vue

How to implement Angular’s ​​HMR function

The above is the detailed content of How to implement DOM insertion node in JS. 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!