简体   繁体   English

根据类和元素类型选择元素

[英]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 loggedintitle 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
  • for every element in that array the array class names is extracted (see aElems[i].className.split ) 对于该数组中的每个元素,都会提取数组类名称(请参阅aElems[i].className.split
  • every class name is then used as property name for an index object 然后将每个类名用作索引对象的属性名
  • the index is then looked up for the two class names (see aElems[i].className.split ) 然后查找索引以查找两个类名(请参阅aElems[i].className.split

Technically that's not one class, it's two classes: title and loggedin . 从技术上讲,这不是一个类,它是两个类: titleloggedin 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这样的框架会更方便。

我知道这是一个老问题,但如果您想知道jQuery如何选择元素,您可以查看其独立选择器引擎Sizzle.js的来源,这些引擎多年来一直由很多聪明的人开发,他们花了很多处理性能的时间:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM