How do i change html class with javascript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How do i change html class with javascript?

I have a img tag with A class how to change it to B class

12th Dec 2017, 2:10 AM
RazoraKun
RazoraKun - avatar
6 Answers
+ 1
can i select class from option value?
12th Dec 2017, 2:20 AM
RazoraKun
RazoraKun - avatar
+ 7
I like the addEventListener approach. I was thinking of doing something like this: <select onchange="update(this)"> ... </select> function update(elSelected) { alert(elSelected.value); // "red", "blue" } Embedding javascript in HTML is not the most clear, but I think there's an "onchange" event (not tested before posting, just an idea for you two)
12th Dec 2017, 4:55 AM
Kirk Schafer
Kirk Schafer - avatar
+ 3
im sorry... how to change P class from red to blue if i choose Blue in select option <select name="color"> <Option value="red">Red</option> <option value="blue">Blue</option> </select> <p class="Red> change to blue</p>
12th Dec 2017, 2:29 AM
RazoraKun
RazoraKun - avatar
+ 3
Ah, try something like this. The code basically adds a listener to the select, so every time you click on it it will verify what you selected and change the class. var select = document.getElementById('example'); //Again, you can get the item as you like, I do it for convenience select.addEventListener('click', function() { var selectedOption = this.options[select.selectedIndex]; var p = document.getElementsByTagName('p'); if (selectedOption.value == 'red') { p[0].className = 'red'; } else { p[0].className = 'blue'; } });
12th Dec 2017, 4:16 AM
Mickel
Mickel - avatar
+ 2
JS: document.getElementById("MyElement").className = "MyClass"; JQuery: $('#MyElement').removeClass('MyOldClass'); $('#MyElement').addClass('MyClass'); (You can get the item by the name of the tag, the ID or the class. In this case I used the ID by habit)
12th Dec 2017, 2:18 AM
Mickel
Mickel - avatar
+ 1
I don't understand your question :/
12th Dec 2017, 2:23 AM
Mickel
Mickel - avatar