1

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

2 Answers2

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