[英]Select elements based on class and element type
How can I select all elements within an HTML document with a specific class and specific element type? 如何选择具有特定类和特定元素类型的HTML文档中的所有元素?
I'm trying to select all anchors with the class title loggedin
from an HTML document (and then open them within the browser). 我正在尝试从HTML文档中选择
title loggedin
类title loggedin
所有锚点(然后在浏览器中打开它们)。 These are within parragraphs with the class title
. 这些是与类别
title
parragraphs。
They are leafs in the following DOM tree: 它们是以下DOM树中的叶子:
+ body
+ div class='content'
+ div id='siteTable' class='sitetable linklisting'
+ div class='thing id-t3_xxxx xxx xxx link'
+ div class='entry unvoted'
+ p class='title'
+ a class='title loggedin '
Where x
indicates variable content. 其中
x
表示可变内容。
(I'm looking to do this in raw JavaScript, ie, not in jQuery.) (我希望在原始JavaScript中执行此操作,即不在jQuery中。)
Try this: 尝试这个:
var aElems = document.getElementsByTagName("a");
for (var i=0; i<aElems.length; ++i) {
var classesArr = aElems[i].className.split(/\s+/),
classesObj = {};
for (var j=0; j<classesArr.length; ++j) {
classesObj[classesArr[i]] = true;
}
if (classesObj.hasOwnProperty("title") && classesObj.hasOwnProperty("loggedin")) {
// action
}
}
Some explanation: 一些解释:
document.getElementsByTagName
returns an array of elements of the given type (in this case a
) document.getElementsByTagName
返回给定类型的元素数组(在本例中为a
) aElems[i].className.split
) aElems[i].className.split
) aElems[i].className.split
) aElems[i].className.split
) Technically that's not one class, it's two classes: title
and loggedin
. 从技术上讲,这不是一个类,它是两个类:
title
和loggedin
。 You can use document.getElementsByClassName()
for that. 您可以使用
document.getElementsByClassName()
。
var elements = document.getElementsByClassName("title loggedin");
You can pass two classes to that method. 您可以将两个类传递给该方法。
Fetching all elements of a certain tag type using document.getElementsByTagName()
and walking through the list should work. 使用
document.getElementsByTagName()
获取某个标记类型的所有元素并遍历列表应该有效。 With multiple classes you'd have to parse the className
property (which will contain the full string title loggedin
) manually. 对于多个类,您必须手动解析
className
属性(将包含已title loggedin
的完整字符串title loggedin
)。
I assume you have good reason to do this in pure JavaScript; 我假设您有充分的理由在纯JavaScript中执行此操作; it would be much more convenient using a framework like jQuery or Prototype.
使用像jQuery或Prototype这样的框架会更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.