Why can't the class attribute assign inline javascript?

<html> <head> <style> .tagging{ border: 1px solid black; width : 20px; height: 30px; } </style> <script> window.onload = function(){ var div = document.getElementsByTagName("div"); div[0].class = "tagging"; } </script> </head> <body> <div></div> </body> </html> 

This is my code. I wonder why this does not work when I assign a class attribute through javascript, but it works when I assign inline directly in html

 <div class="tagging"></div> 
+4
source share
3 answers

You need to use className .

Try:

 div[0].className = "tagging"; 

If you want to add this class to an existing one, you can use:

 div[0].className += " tagging"; // adding white-space is important 

Demo here

To read: MDN class_name .

+6
source

use className , so change:

 var div = document.getElementsByTagName("div"); div[0].class = "tagging"; 

to

 var div = document.getElementsByTagName("div"); div[0].className = "tagging"; 

Demo :: jsFiddle

+3
source
 <div id="div1" class="someclass"> <img ... id="image1" name="image1" /> </div> Then var d = document.getElementById("div1"); d.className = d.className + " otherclass"; 
0
source

Source: https://habr.com/ru/post/1500650/


All Articles