-3

I have some HTML :

<div class="blah">
<div class="blah">

And I want to get all the divs with class 'blah'

var result = document.querySelector('.blah');

However the result is just the first element.

How do I get ALL elements?

Fiddle :

https://jsfiddle.net/pa5jpvsk/

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225

3 Answers3

1

This is a hard one: querySelectorAll() http://www.w3schools.com/jsref/met_document_queryselectorall.asp

CoderPi
  • 12,985
  • 4
  • 34
  • 62
1

Instead use document.querySelectorAll which returns you a list.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Mark E
  • 721
  • 6
  • 16
1

You can do it with querySelectorALL

var result = document.querySelectorAll('.blah');
console.log(result.length)
<div class="blah">
<div class="blah">

Result are showed in the console.

With jQuery you can simplify it to:

$('.blah');

Adrian Menendez
  • 480
  • 4
  • 12
  • `var $ = function(sel) { return document.querySelectorAll(sel); };` jQuery is so incredibly unnecessary and completely irrelevant here. –  Dec 01 '15 at 11:42