Three ways to create elements:
document.write()
element.innerHTML
document.createElement()
1. document.write()
Implementation code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>btn</button>
<p>段落</p>
<div class="inner">inner</div>
<div class="create">create</div>
<script>
var btn = document.querySelector('button');
btn.onclick = function() {
document.write('<div>123</div>');
}
</script>
</body>
</html>
Initial page:
Realization effect: After
clicking the "btn" button:
Obviously, using the document.write()
create element, if the page document flow is loaded, calling the event will cause the page to be redrawn
2. element.innerHTML
(1) String splicing method:
Implementation code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>btn</button>
<p>段落</p>
<div class="inner">inner</div>
<div class="create">create</div>
<script>
var inner = document.querySelector('.inner');
inner.innerHTML += ' <a href="#">我是后来加的链接,字符串拼接方式</a>';
</script>
</body>
</html>
Realization effect:
(2) How to add array elements:
Implementation code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>btn</button>
<p>段落</p>
<div class="inner">inner</div>
<div class="create">create</div>
<script>
var inner = document.querySelector('.inner');
// 创建空数组
var arr = [];
// 将需要添加的元素,添加到数组中
arr.push('<a href="#"> 我是后来加的链接,数组方式</a>');
// 将数组转化为字符串,再给到inner节点
inner.innerHTML = arr.join('');
</script>
</body>
</html>
Realization effect:
3. document.createElement()
Implementation code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>btn</button>
<p>段落</p>
<div class="inner">inner</div>
<div class="create">create</div>
<script>
var create = document.querySelector('.create');
var a = document.createElement('a');
create.appendChild(a);
</script>
</body>
</html>
Realization effect:
to sum up:
document.write
It is a content stream that directly writes content to the page, but after the document stream is executed, it will cause the page to be redrawn .innerHTML
It is to write the content to a DOM node , which will not cause the page to be redrawn. Create multiple elements, the structure is slightly more complicated. It can be added in string splicing mode or array mode .createElement()
Create multiple elements to make the structure clearer.