1

Hi can someone show me how is possible to check if some class exists and if is true return a variable? (div, a, span, b, p, etc.) without div id and without jquery. I am new in javascript, thanks

My prototype example

var button  = ".button {border: 1px solid #000, padding 1em}";

if ( button class exist in current html)
{ print var button }
Blackhero
  • 31
  • 5
  • What exactly does "some class exists in html document" mean? Elements that have that class? – Ram May 18 '15 at 05:26
  • Try using document.querySelectorAll() :- https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll – Ramanathan Muthuraman May 18 '15 at 05:26
  • possible duplicate of [How to getElementByClass instead of GetElementById with Javascript?](http://stackoverflow.com/questions/1933602/how-to-getelementbyclass-instead-of-getelementbyid-with-javascript) – Steve May 18 '15 at 05:26
  • yes if the document have x class and if they exist print a variable – Blackhero May 18 '15 at 05:26
  • @RamanathanMuthuraman: `document.querySelector(klass)` is easier than `document.querySelectorAll(klass).length` :) – Amadan May 18 '15 at 05:26

3 Answers3

3

getElementsByClassName is what you're looking for. It returns an array like object which you can simply check it's length to see if the class exists.

Tony
  • 351
  • 3
  • 19
1

you can check it with

var x = document.getElementsByClassName("example");
if(x!==null) 
{
  //do something
}
Karthikeyan
  • 381
  • 8
  • 19
  • i test the solution but when i delete the example class the script continue show the alert i use to test with your example, thanks for your awnser! – Blackhero May 18 '15 at 05:46
  • 1
    The result of `getElementsByClassName` will always be a `HTMLCollection` (possibly with `.length == 0`), never `null`. – Amadan May 18 '15 at 05:49
1
document.getElementsByClassName('button');

This returns empty if no element was found in the document. You could use it to check.

Ely
  • 10,860
  • 4
  • 43
  • 64
  • `document.getElementsByClassName('button')` or `document.querySelectorAll('.button') (or `querySelectorAll`). Note which one has the dot, and which hasn't. – Amadan May 18 '15 at 05:50
  • Thanks, minor issue with copy & paste. – Ely May 18 '15 at 06:04