querySelector() 在不在文档上调用时做什么?

huangapple go评论63阅读模式
英文:

What does querySelector() do when not called on the document?

问题

MDN模板文档中,我看到了这样的代码:clone.querySelectorAll("td");,出于好奇,我写了JS代码片段如下:document.querySelector(".para").append(" hello");h5.querySelector(".para").append(" world"),试图将"world"附加到"hello"后面,但出现了错误。

请解释一下非document(dot)querySelector样式的概念及其用法,以纠正我的错误。

// 创建一个新的h5元素
h5 = document.createElement('h5');
h5.textContent = "text updated";
h5.className = "first";

// 这里的查询使用了document.querySelector,它会在整个文档中查找匹配的元素
document.querySelector(".para").append(" hello"); // 这行代码正常工作

// 但这里的查询使用了h5.querySelector,它会在h5元素内部查找匹配的元素
// 由于h5元素内部没有匹配的元素,会返回null,因此出现错误
h5.querySelector(".para").append(" world"); // 控制台会报null值的错误,意味着没有找到任何匹配的元素
英文:

In the MDN template docs I saw code as clone.querySelectorAll("td");, so out of curiosity I wrote JS code snippet as document.querySelector(".para").append(" hello");h5.querySelector(".para").append(" world") to try to append 'world' to 'hello', but got an error.

Please explain the concept of a non-document(dot)querySelector style and its usage to rectify my error

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

h5=document.createElement(&#39;h5&#39;);
h5.textContent= &quot;text updated&quot;;
h5.className= &quot;first&quot;;
document.querySelector(&quot;.para&quot;).append(&quot; hello&quot;);//works
h5.querySelector(&quot;.para&quot;).append(&quot; world&quot;);//console log error of value null meaning nothing selected

<!-- language: lang-html -->

&lt;p class=&quot;para&quot;&gt; Test: &lt;/p&gt;

<!-- end snippet -->

答案1

得分: 1

调用querySelector()方法时,它会限制搜索范围为元素的后代元素,而不是搜索整个DOM。

你需要在<h5>内插入<p class="para">,这样才能找到它。如果你想查看结果,你需要将h5添加到文档中。

英文:

Calling querySelector() on an element restricts the search to the element's descendants, rather than searching the entire DOM.

You need to insert a &lt;p class=&quot;para&quot;&gt; inside the &lt;h5&gt; so it will be found. And if you want to see the results, you need to append h5 to the document.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let h5=document.createElement(&#39;h5&#39;);
let p = document.createElement(&#39;p&#39;);
p.textContent = &#39;Test2:&#39;;
p.classList.add(&#39;para&#39;);
h5.appendChild(p);
document.body.appendChild(h5);
h5.className= &quot;first&quot;;
document.querySelector(&quot;.para&quot;).append(&quot; hello&quot;);//works
h5.querySelector(&quot;.para&quot;).append(&quot; world&quot;);

<!-- language: lang-html -->

&lt;p class=&quot;para&quot;&gt; Test: &lt;/p&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月7日 05:50:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定