Javascript 如何通过类名获取子元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12166753/
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
How to get child element by class name?
提问by spyderman4g63
I'm trying to get the child span that has a class = 4. Here is an example element:
我正在尝试获取具有 class = 4 的子跨度。这是一个示例元素:
<div id="test">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
<span class="four"></span>
</div>
The tools I have available are JS and YUI2. I can do something like this:
我可用的工具是 JS 和 YUI2。我可以做这样的事情:
doc = document.getElementById('test');
notes = doc.getElementsByClassName('four');
//or
doc = YAHOO.util.Dom.get('#test');
notes = doc.getElementsByClassName('four');
These do not work in IE. I get an error that the object (doc) doesn't support this method or property (getElementsByClassName). I've tried a few examples of cross browser implementations of getElementsByClassName but I could not get them to work and still got that error.
这些在 IE 中不起作用。我收到一个错误,指出对象 (doc) 不支持此方法或属性 (getElementsByClassName)。我已经尝试了几个 getElementsByClassName 跨浏览器实现的例子,但我无法让它们工作并且仍然得到那个错误。
I think what I need is a cross browser getElementsByClassName or I need to use doc.getElementsByTagName('span') and loop through until I find class 4. I'm not sure how to do that though.
我想我需要的是跨浏览器 getElementsByClassName 或者我需要使用 doc.getElementsByTagName('span') 并循环直到找到第 4 类。不过我不知道该怎么做。
采纳答案by Jo?o Silva
Use doc.childNodes
to iterate through each span
, and then filter the one whose className
equals 4
:
使用doc.childNodes
通过每个迭代span
,然后筛选其一个className
等号4
:
var doc = document.getElementById("test");
var notes = null;
for (var i = 0; i < doc.childNodes.length; i++) {
if (doc.childNodes[i].className == "4") {
notes = doc.childNodes[i];
break;
}
}
?
?
回答by Alberto Clar Brines
Use querySelector and querySelectorAll
使用 querySelector 和 querySelectorAll
var testContainer = document.querySelector('#test');
var fourChildNode = testContainer.querySelector('.four');
IE9 and upper
IE9及以上
;)
;)
回答by Augie Gardner
The accepted answer only checks immediate children. Often times we're looking for any descendants with that class name.
接受的答案只检查直接的孩子。很多时候,我们正在寻找具有该类名的任何后代。
Also, sometimes we want any child that containsa className.
此外,有时我们想要任何包含className 的孩子。
For example: <div class="img square"></div>
should match a search on className "img", even though it's exactclassName is not "img".
例如:<div class="img square"></div>
应该匹配对 className "img" 的搜索,即使它的确切className 不是 "img"。
Here's a solution for both of these issues:
这是针对这两个问题的解决方案:
Find the first instance of a descendant element with the class className
查找具有该类的后代元素的第一个实例 className
function findFirstChildByClass(element, className) {
var foundElement = null, found;
function recurse(element, className, found) {
for (var i = 0; i < element.childNodes.length && !found; i++) {
var el = element.childNodes[i];
var classes = el.className != undefined? el.className.split(" ") : [];
for (var j = 0, jl = classes.length; j < jl; j++) {
if (classes[j] == className) {
found = true;
foundElement = element.childNodes[i];
break;
}
}
if(found)
break;
recurse(element.childNodes[i], className, found);
}
}
recurse(element, className, false);
return foundElement;
}
回答by Hamza Dahmoun
Use element.querySelector(). Lets assume: 'myElement' is the parent element you already have. 'sonClassName' is the class of the child you are looking for.
使用 element.querySelector()。让我们假设: 'myElement' 是您已经拥有的父元素。'sonClassName' 是您正在寻找的孩子的班级。
let child = myElement.querySelector('.sonClassName');
For more info, visit: https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
更多信息,请访问:https: //developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
回答by Korikulum
You could try:
你可以试试:
notes = doc.querySelectorAll('.4');
or
或者
notes = doc.getElementsByTagName('*');
for (var i = 0; i < notes.length; i++) {
if (notes[i].getAttribute('class') == '4') {
}
}
回答by Christian J?rgensen
To me it seems like you want the fourth span. If so, you can just do this:
对我来说,您似乎想要第四个跨度。如果是这样,你可以这样做:
document.getElementById("test").childNodes[3]
or
或者
document.getElementById("test").getElementsByTagName("span")[3]
This last one ensures that there are not any hidden nodes that could mess it up.
最后一个确保没有任何隐藏的节点可能会弄乱它。
回答by Oriol
But be aware that old browsers doesn't support getElementsByClassName
.
但请注意,旧浏览器不支持getElementsByClassName
.
Then, you can do
然后,你可以做
function getElementsByClassName(c,el){
if(typeof el=='string'){el=document.getElementById(el);}
if(!el){el=document;}
if(el.getElementsByClassName){return el.getElementsByClassName(c);}
var arr=[],
allEls=el.getElementsByTagName('*');
for(var i=0;i<allEls.length;i++){
if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
}
return arr;
}
getElementsByClassName('4','test')[0];
It seems it works, but be aware that an HTML class
看起来它有效,但请注意 HTML 类
- Must begin with a letter: A-Z or a-z
- Can be followed by letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_")
- 必须以字母开头:AZ 或 az
- 后面可以跟字母 (A-Za-z)、数字 (0-9)、连字符 ("-") 和下划线 ("_")
回答by Guffa
Use the name of the id with the getElementById
, no #
sign before it. Then you can get the span
child nodes using getElementsByTagName
, and loop through them to find the one with the right class:
使用 id 的名称,前面getElementById
没有#
符号。然后,您可以使用 获取span
子节点getElementsByTagName
,并遍历它们以找到具有正确类的节点:
var doc = document.getElementById('test');
var c = doc.getElementsByTagName('span');
var e = null;
for (var i = 0; i < c.length; i++) {
if (c[i].className == '4') {
e = c[i];
break;
}
}
if (e != null) {
alert(e.innerHTML);
}
回答by Guffa
In my opinion, each time you can, you should use Array and its methods. They are much, much faster then looping over the whole DOM / wrapper, or pushing stuff into empty array. Majority of solutions presented here you can call Naive as described here (great article btw):
在我看来,每次可以时,都应该使用 Array 及其方法。它们比遍历整个 DOM / 包装器或将内容推入空数组要快得多。此处介绍的大多数解决方案您都可以按照此处所述调用 Naive(顺便说一句很棒的文章):
https://medium.com/@chuckdries/traversing-the-dom-with-filter-map-and-arrow-functions-1417d326d2bc
https://medium.com/@chuckdries/traversing-the-dom-with-filter-map-and-arrow-functions-1417d326d2bc
My solution: (live preview on Codepen: https://codepen.io/Nikolaus91/pen/wEGEYe)
我的解决方案:(在 Codepen 上实时预览:https://codepen.io/Nikolaus91/pen/wEGEYe )
const wrapper = document.getElementById('test') // take a wrapper by ID -> fastest
const itemsArray = Array.from(wrapper.children) // make Array from his children
const pickOne = itemsArray.map(item => { // loop over his children using .map() --> see MDN for more
if(item.classList.contains('four')) // we place a test where we determine our choice
item.classList.add('the-chosen-one') // your code here
})
回答by Marselus Chia
The way i will do this using jquery is something like this..
我将使用 jquery 执行此操作的方式是这样的..
var targetedchild = $("#test").children().find("span.four");
vartargetedchild = $("#test").children().find("span.four");