1.总结如下:
-
创建新节点的方法:
document.createElement(tag)
—— 用给定的标签创建一个元素节点,document.createTextNode(value)
—— 创建一个文本节点(很少使用),elem.cloneNode(deep)
—— 克隆元素,如果deep==true
则与其后代一起克隆。
-
插入和移除节点的方法:
node.append(...nodes or strings)
—— 在node
末尾插入,node.prepend(...nodes or strings)
—— 在node
开头插入,node.before(...nodes or strings)
—— 在node
之前插入,node.after(...nodes or strings)
—— 在node
之后插入,node.replaceWith(...nodes or strings)
—— 替换node
。node.remove()
—— 移除node
。
文本字符串被“作为文本”插入。
-
这里还有“旧式”的方法:
parent.appendChild(node)
parent.insertBefore(node, nextSibling)
parent.removeChild(node)
parent.replaceChild(newElem, node)
这些方法都返回
node
。 -
在
html
中给定一些 HTML,elem.insertAdjacentHTML(where, html)
会根据where
的值来插入它:"beforebegin"
—— 将html
插入到elem
前面,"afterbegin"
—— 将html
插入到elem
的开头,"beforeend"
—— 将html
插入到elem
的末尾,"afterend"
—— 将html
插入到elem
后面。
另外,还有类似的方法,elem.insertAdjacentText
和 elem.insertAdjacentElement
,它们会插入文本字符串和元素,但很少使用。
-
要在页面加载完成之前将 HTML 附加到页面:
document.write(html)
页面加载完成后,这样的调用将会擦除文档。多见于旧脚本。
2.示例:
2.1 编写一个函数 createTree
,从嵌套对象创建一个嵌套的 ul/li
列表(list)。
例如:
let data = {
"Fish": {
"trout": {},
"salmon": {}
},
"Tree": {
"Huge": {
"sequoia": {},
"oak": {}
},
"Flowering": {
"apple tree": {},
"magnolia": {}
}
}
};
语法:
let container = document.getElementById('container');
createTree(container, data); // 将树创建在 container 中
2.1.1 使用 innerHTML 的解决方案
代码如下:
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
<script>
let data = {
"Fish": {
"trout": {},
"salmon": {}
},
"Tree": {
"Huge": {
"sequoia": {},
"oak": {}
},
"Flowering": {
"apple tree": {},
"magnolia": {}
}
}
};
function createTree(container, obj) {
container.innerHTML = createTreeText(obj);
}
function createTreeText(obj) { // standalone recursive function
let li = '';
let ul;
for (let key in obj) {
li += '<li>' + key + createTreeText(obj[key]) + '</li>';
}
if (li) {
ul = '<ul>' + li + '</ul>'
}
return ul || '';
}
createTree(container, data);
</script>
</body>
</html>
2.1.2 使用 DOM 的解决方案
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
<script>
let data = {
"Fish": {
"trout": {},
"salmon": {}
},
"Tree": {
"Huge": {
"sequoia": {},
"oak": {}
},
"Flowering": {
"apple tree": {},
"magnolia": {}
}
}
};
function createTree(container, obj) {
container.append(createTreeDom(obj));
}
function createTreeDom(obj) {
// if there's no children, then the call returns undefined
// and the <ul> won't be created
if (!Object.keys(obj).length) return;
let ul = document.createElement('ul');
for (let key in obj) {
let li = document.createElement('li');
li.innerHTML = key;
let childrenUl = createTreeDom(obj[key]);
if (childrenUl) {
li.append(childrenUl);
}
ul.append(li);
}
return ul;
}
let container = document.getElementById('container');
createTree(container, data);
</script>
</body>
</html>
2.2 在树中显示后代
<!DOCTYPE HTML>
<html>
<body>
<ul>
<li>Animals
<ul>
<li>Mammals
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
</ul>
</li>
<li>Other
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<ul>
<li>Aquarium
<ul>
<li>Guppy</li>
<li>Angelfish</li>
</ul>
</li>
<li>Sea
<ul>
<li>Sea trout</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
let lis = document.getElementsByTagName('li');
for (let li of lis) {
// get the count of all <li> below this <li>
let descendantsCount = li.getElementsByTagName('li').length;
if (!descendantsCount) continue;
// add directly to the text node (append to the text)
li.firstChild.data += ' [' + descendantsCount + ']';
}
</script>
</body>
</html>
2.3 创建一个日历
<!DOCTYPE HTML>
<html>
<head>
<style>
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 3px;
text-align: center;
}
th {
font-weight: bold;
background-color: #E6E6E6;
}
</style>
</head>
<body>
<div id="calendar"></div>
<script>
function createCalendar(elem, year, month) {
let mon = month - 1; // months in JS are 0..11, not 1..12
let d = new Date(year, mon);
let table = '<table><tr><th>MO</th><th>TU</th><th>WE</th><th>TH</th><th>FR</th><th>SA</th><th>SU</th></tr><tr>';
// spaces for the first row
// from Monday till the first day of the month
// * * * 1 2 3 4
for (let i = 0; i < getDay(d); i++) {
table += '<td></td>';
}
// <td> with actual dates
while (d.getMonth() == mon) {
table += '<td>' + d.getDate() + '</td>';
if (getDay(d) % 7 == 6) { // sunday, last day of week - newline
table += '</tr><tr>';
}
d.setDate(d.getDate() + 1);
}
// add spaces after last days of month for the last row
// 29 30 31 * * * *
if (getDay(d) != 0) {
for (let i = getDay(d); i < 7; i++) {
table += '<td></td>';
}
}
// close the table
table += '</tr></table>';
elem.innerHTML = table;
}
function getDay(date) { // get day number from 0 (monday) to 6 (sunday)
let day = date.getDay();
if (day == 0) day = 7; // make Sunday (0) the last day
return day - 1;
}
createCalendar(calendar, 2012, 9);
</script>
</body>
</html>
参考文章:现代JavaScript教程