tags:

views:

75

answers:

3

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

+4  A: 

Try this:

var aElems = document.getElementsByTagName("a");
for (var i=0; i<aElemes.length; ++i) {
    var classesArr = aElements[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 aElements[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 aElements[i].className.split)
Gumbo
It seems you're relying on `Array.prototype.indexOf` which isn't supported in all browsers...
J-P
@J-P: Good argument. I changed it so it doesn’t require that method.
Gumbo
I ultimately went for a more simple solution to that posted. Cheers!
Beau Martínez
+2  A: 

Fetching all elements of a certain tag type using document.getElementsByTagName() and walking through the list should work. With multiple classes you'd have to parse the className property (which will contain the full string title loggedin) manually.

I assume you have good reason to do this in pure JavaScript; it would be much more convenient using a framework like jQuery or Prototype.

Pekka
Naturally, it'd be easier in jQuery, but I'd prefer to know how to walk before I run! ;)
Beau Martínez
@Beau that's a good attitude!
Pekka
+2  A: 

Technically that's not one class, it's two classes: title and loggedin. You can use document.getElementsByClassName() for that.

var elements = document.getElementsByClassName("title loggedin");

You can pass two classes to that method.

cletus
It's worth noting that `getElementsByClassName()` has compatibility implications (at this point in time): http://www.quirksmode.org/dom/w3c_core.html#gettingelements
Tomalak