javascript 元素javascript中的getElementsByTagName

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9849848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:01:59  来源:igfitidea点击:

getElementsByTagName within an element javascript

javascriptdom

提问by Sam Adamsh

Why does the following return 0?

为什么以下返回0?

 <p id="g">
 <div>kk</div>
 <div>ee</div>
 <div>jff</div>
 </p>


  <script type="text/javascript">
  var ii = document.getElementById("g");
  var hh = ii.getElementsByTagName('div');
  document.write(hh.length);
  </script>

回答by Tomalak

Because you can't have a <div>in a <p>. Paragraphs can only have inline elementsas children.

因为你不能有<div>a <p>。段落只能有内联元素作为子元素

As soon as the parser encounters a <div>, it auto-closes the <p>.

一旦解析器遇到<div>,它就会自动关闭<p>

Compare

比较

<p id="g">
  <span>kk</span>
  <div>ee</div>
  <div>jff</div>
</p>

<script type="text/javascript">
  var ii = document.getElementById("g");
  var hh = ii.getElementsByTagName('span');
  alert(hh.length);
</script>?