Home > Web Front-end > JS Tutorial > Add element new node using JS

Add element new node using JS

亚连
Release: 2018-06-06 11:36:31
Original
1926 people have browsed it

This article mainly introduces the JS method of simply adding new element nodes, and analyzes the creation, addition, cloning and other related operation techniques of javascript for page element nodes in the form of examples. Friends in need can refer to it

The example in this article describes how to simply add new nodes of elements using JS. Share it with everyone for your reference, the details are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>www.jb51.net - JS添加新节点的几种方法</title>
</head>
<body>
<p id="d">
<span id="s">
  1234567890
</span>
</p>
</body>
<script type="text/javascript">
  //首先找到Id为d的元素
  var d=document.getElementById(&#39;d&#39;);
  //创建一个节点
  var a=document.createElement(&#39;a&#39;);
  //设置a的属性
  a.href=&#39;https://www.baidu.com/&#39;;
  a.innerText=&#39;ggggg&#39;;
  //添加元素  将创建的节点添加到Id为d的p里
  d.appendChild(a);
  //在指定节点前插入新节点
  var p=document.createElement(&#39;p&#39;);
  //添加文本内容
  p.innerText=&#39;ppppppppppppppppp&#39;;
  //d.appendChild(p);
  //参数1:要添加的元素 参数2:要放到哪个节点的前面
  d.insertBefore(p,a);
  //获取目标元素
  var s=document.getElementById(&#39;s&#39;);
  //克隆新元素
  var spanc= s.cloneNode(true);//默认参数是false
  d.appendChild(spanc);
</script>
</html>
Copy after login

Screenshot of the running effect:

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. help.

Related articles:

Some problems with WeChat JSSDK when requesting different pages through ajax?

Detailed interpretation of Node timer knowledge

Detailed analysis of the Generator function in Es6

The above is the detailed content of Add element new node using 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