Capture current class in a variable

0

I'm trying to capture the value of a class tag in a variable so I can use it in a js, the problem is that the state of this class is changing, and I need to capture the value I have at the moment

I'm trying to use var x = document.getElementsByClassName() , but I still can not capture the current class in a variable.

    
asked by alec_brac 24.07.2018 в 22:33
source

3 answers

0

Using Jquery you can use

 var x = $(elem).attr("class");

That gives you the name of the class.

    
answered by 24.07.2018 в 22:41
0

The code that you entered what it does is find the elements that have that class name.

   var lsMetal = document.getElementsByClassName("classMetal");

What would give you a list of elements, which you could manipulate in the following way

 var primerMetal = lsMetal[0];

On the other hand what you are looking for does not come by this way, as they mentioned above if what you are looking for is the name of the class of an element, with simple javascript.

var myclass = document.getElementById("myDIV").className
    
answered by 24.07.2018 в 22:53
0

Dear,

What the method you are using is to obtain all the elements that have the value that you give as a parameter.

For example:

<div id="test" class="xclass">88</div>

var x = document.getElementsByClassName("xclass");

With that you would get the div that has the class that has the value you give it.

In the question you do not understand what you are looking for.

If what you need is to obtain the value of the class attribute of a certain element, you must first determine how to find the element in the DOM, for example if it has an id it can be done in the following way:

document.getElementById("test").getAttribute("class")

will give you similar values to the following:

xclass

If what you need is the value of a tag according to the name of the class for the same case it would be like this.

document.getElementsByClassName ("xclass"). innerHTML

This will give you: 88

Greetings!

    
answered by 24.07.2018 в 23:10