-1

As the title quotes, how do I get the class of a HTML element in Javascript when you know its innerHTML. For instance, if you have a button element, and its class is "classTest" and its innerHTML is "Click me" tag:

I got the innerHTML "Click me" and stored it in a var in my Javascript. But i want to know if it has the CSS class "classTest" or not.. Is there any way of doing it in Javascript? I have not found something that answers this question, if you know then please provide me with it. Thanks!

Pajala
  • 131
  • 10
  • If you're using jquery, the're is a function called hasClass that makes exactly what you want. [1]: https://api.jquery.com/hasclass/ – Enrique Quero Dec 16 '15 at 12:47
  • 2
    store the DOMObject into the var instead of just its `innerHTML`., if you then need again its innerHTML just do `mySaveButton.innerHTML` – Kaiido Dec 16 '15 at 12:47
  • Do you want to know the class if you click on the button, or do you need to iterate over the entire DOM to find a button with that content and then find its class. The second way is bad, btw. – Andy Dec 16 '15 at 12:48
  • http://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class Check it – Gaurav Rai Dec 16 '15 at 12:48
  • 1
    You can refer [MDN - Element.classList](https://developer.mozilla.org/en/docs/Web/API/Element/classList) – Rajesh Dec 16 '15 at 12:49
  • [ClassList stack answer....](http://stackoverflow.com/questions/5085567/hasclass-with-javascript-or-site-with-jquery-to-javascript-translation) – yjs Dec 16 '15 at 12:50
  • 1
    I agree with @Kaiido You should definatly not store the value, you should store a reference to the object. – Patrick Schumacher Dec 16 '15 at 12:57

1 Answers1

4

You do not usually / you should not search for elements or their attributes based on their content. That is slow and unreliable.

Instead you should give your button element an id for example, and then use something like:

document.querySelector('#idofbuttonelement').classList.contains('className');

Also here are some other jQuery features in pure JavaScript: https://github.com/oneuijs/You-Dont-Need-jQuery

Swiffy
  • 4,401
  • 2
  • 23
  • 49
  • Yeah I thought about it. But im using angular.js and the I get the innerHTML data from a object with ng-repeat.. So it has like 10 buttons, and I want to see if its clicked or not because if its clicked, then it class changes. Did you get what i mean? – Pajala Dec 16 '15 at 12:50
  • @Pajala There is most likely something done silly, if you have ran into a scenario like this. You should probably redesign the part you a describing as problematic and, for example, implement some kind of solution to come up with the actual button elements instead of innerHTML data. – Swiffy Dec 16 '15 at 13:05