-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!

7
  • If you're using jquery, the're is a function called hasClass that makes exactly what you want. [1]: api.jquery.com/hasclass Commented Dec 16, 2015 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 Commented Dec 16, 2015 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. Commented Dec 16, 2015 at 12:48
  • 1
    You can refer MDN - Element.classList Commented Dec 16, 2015 at 12:49
  • 1
    I agree with @Kaiido You should definatly not store the value, you should store a reference to the object. Commented Dec 16, 2015 at 12:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.