gpt4 book ai didi

javascript - * 选择器适用于 getElementsByTagName(),但不适用于 javascript 中的 getElementsByClassName()?

转载 作者:行者123 更新时间:2023-11-29 21:55:11 25 4
gpt4 key购买 nike

我可以在 getElementsByTags() 中使用“*”选择器,但不能在 getElementsByClassName() 或 getElementByID() 中使用。

谁能解释一下为什么?而且,无论如何在 javascript 方法中使用子字符串选择器,即 (getElementsByClassName("*profile") 来选择类名包含“profile”的元素?

下面是我的代码:

<body>
<div class="yahoo">
</div>
<p class="yahoo">
</p>
<ul class="yahoo">
</ul>

<div class="yahoo">
</div>


<input type='text'>
<script type="text/javascript">
function select(){
var elements = document.getElementsByTagName("*")
var elements2 = document.getElementsByClassName("*")
console.log(elements)
}

select()
</script>

最佳答案

此行为符合 DOM-Level-2-Core specification其中指出:

getElementsByTagName
  Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.
  Parameters
name of type DOMString
The name of the tag to match on. The special value "*" matches all tags.

对于 getElementsByClassName 方法,字符 * 没有特殊的概念,按字面意思处理为类名。

更新。解决你的第二个问题:

is there anyway to use substring selector in javascript methods ie (getElementsByClassName("*profile") to select elements whose class name includes 'profile'?

您不能使用 getElementsByClassName 但是可以为此使用另一个非常有用的 querySelectorAll 方法:

document.querySelectorAll('[class*="profile"]');

关于javascript - * 选择器适用于 getElementsByTagName(),但不适用于 javascript 中的 getElementsByClassName()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26827979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com