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.)
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
)aElems[i].className.split
)aElems[i].className.split
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With