I want to use JS to find all items with an A
tag, and the class Titanic
. How would i go about this without querySelector. I want the method to be fast. So preferably no loops.
Asked
Active
Viewed 54 times
-1

BoltClock
- 700,868
- 160
- 1,392
- 1,356

Nicky Smits
- 2,980
- 4
- 20
- 27
-
Apologies but, There's alot of resources on this question on SO, let alone the web. – MackieeE Apr 07 '14 at 11:27
-
I couldnt find any that didnt point to QuerySelector. So unless you can find such a link your comment is mood and your downvote is useless. – Nicky Smits Apr 07 '14 at 11:28
2 Answers
2
You won't get away from loops.
You can use the document.links
collection that already contain all the links in the page, and check the class name of each:
var el = [];
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].className == 'Titanic') {
el.push(document.links[i]);
}
}
Demo: http://jsfiddle.net/TrhCG/
Note: The links
collection only contains actual links, i.e. anchor tags (and area tags) with a href
attribute. Also, the way to compare the class name only works if the element contains only that class name.

Guffa
- 687,336
- 108
- 737
- 1,005
-
1+1, but [*document.links*](http://www.w3.org/html/wg/drafts/html/master/dom.html#dom-document-links) only contains links, the OP might want anchors to. ;-) – RobG Apr 07 '14 at 11:38
-
@RobG: Good point, I was thinking about that. I added a note with the limitations of the code. – Guffa Apr 07 '14 at 13:03
0
You can use getElementsByTagName() function to select anchor tags. You can check the classname using .classname property.
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
/*Do something.*/
}
}
Life's much easier if you use jQuery though.

Santosh Achari
- 2,936
- 7
- 30
- 52
-
-
-
-
javascript as such doesn't have a function to get classnames straight. – Santosh Achari Apr 07 '14 at 11:31