javascript 选择器 document.object

javascript selectors document.object

我正在尝试 select 将几个元素添加到我的 html 页面中,我想知道为什么我应该一直使用 "document" 当我定位 [=22] =] 元素例如:

//变量体

var content = document.getElementsByTagName("body"); 

in next variable why I cannot use something like: get all p tags from body

var selector = content.querySelectorAll("p");

instead of using

var selector = document.querySelectorAll("p");

in next variable why I cannot use something like: get all p tags from body

因为getElementsByTagNamereturns一个NodeList,不是一个元素。如果您抓住一个匹配的元素,它就会起作用:

var content = document.getElementsByTagName("body")[0];
// ------------------------------------------------^^^
var paragraphs = content.querySelectorAll("p");

但只需使用 document.body 即可:

var paragraphs = document.body.querySelectorAll("p");

(当然,因为p元素不能在body之外,所以在这个specific中这两个和document.querySelectorAll一样] 案例。)

如果您想要 body 直接子元素 的所有 p 个元素,则:

var paragraphs = document.querySelectorAll("body > p");

因为getElementsByTagNamereturns一个列表元素不是一个,可以用;

var selector = content[0].querySelectorAll("p");

因为getElementsByTagName() returns数组。 所以你应该使用 var content = document.getElementsByTagName("body")[0];

你不能,主要是因为 document.getElementsByTagName return 一个 HTMLCollection。

根据定义,"HTMLCollection interface represents a generic collection (array-like object) of elements (in document order) and offers methods and properties for selecting from the list."

因此,在您的示例中,您需要使用 var content = document.getElementsByTagName("body")[0];document.body(更好)