作为对此的跟进,我经常听到它querySelectorAll()
的不同之处在于它返回一个静态节点列表而不是一个数组,所以我认为这在这里可能会派上用场,而且确实如此:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
</div>
<script>
var links = document.querySelectorAll("a");
for (var i=0, ii=links.length; i<ii; i++)
{
var container = document.createElement("div");
links[i].parentNode.replaceChild(container, links[i]);
container.appendChild(links[i]);
}
</script>
</body>
</html>
此外,替代方法Array.prototype.slice.call(links)
是[].slice.call(links)
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
</div>
<script>
var links = document.getElementsByTagName("a");
var linksCopy = [].slice.call(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
</script>
</body>
</html>
另一个选择是使用[].forEach.call()
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
</div>
<script>
[].forEach.call(document.querySelectorAll('a'), function(el) {
var container = document.createElement("div");
el.parentNode.replaceChild(container, el);
container.appendChild(el);
});
</script>
</body>
</html>
另一个选择,使用 Array.from():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
</style>
</head>
<body>
<div>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
<a href="">link</a>
</div>
<script>
var links = document.getElementsByTagName("a");
var linksCopy = Array.from(links);
for (var i=0; i<linksCopy.length; i++)
{
var container = document.createElement("div");
linksCopy[i].parentNode.replaceChild(container, linksCopy[i]);
container.appendChild(linksCopy[i]);
}
</script>
</body>
</html>