Let I've an HTML markup. How can I find the first element with an appropriate class (e.g. I want to find all divs with class myclass).
Asked
Active
Viewed 52 times
1
-
6`document.querySelectorAll('div.classname')` or when you only need the first hit ``document.querySelector('div.classname')`` – PeeHaa Feb 17 '14 at 13:23
-
all elements or first element? – Arsen Mkrtchyan Feb 17 '14 at 13:24
-
1Oh come on, This is [basic DOM manipulation / access.](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName) – Cerbrus Feb 17 '14 at 13:38
2 Answers
1
document.getElementsByClassName(yourClass)[0]
document.getElementsByClassName(yourClass) gets all of the matching elements in an array, [0] gets the first.
For older IEs:
var match, i = 0,
divs = document.getElementsByTagName('div');
while(!match && divs[i]) {
if(divs[i].className.match(yourClass).length) {
match = divs[i];
} else {
i++;
}
}
console.log(match);
Mild Fuzz
- 29,463
- 31
- 100
- 148
0
document.querySelector('.yourClass')
Should return first instance of the matched selector
Mild Fuzz
- 29,463
- 31
- 100
- 148