Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements based on class and element type

Tags:

javascript

dom

How can I select all elements within an HTML document with a specific class and specific element type?

I'm trying to select all anchors with the class title loggedin from an HTML document (and then open them within the browser). These are within parragraphs with the class title.

They are leafs in the following DOM tree:

+ 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.

(I'm looking to do this in raw JavaScript, ie, not in jQuery.)

like image 678
Humphrey Bogart Avatar asked Dec 03 '22 05:12

Humphrey Bogart


1 Answers

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)
  • for every element in that array the array class names is extracted (see 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)
like image 176
Gumbo Avatar answered Dec 17 '22 11:12

Gumbo