<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 it doesn't work when I assign class attribute via javascript, but it works when I assign inline directly in html
<div class="tagging"></div>
Inline elements are those which only occupy the space bounded by the tags defining the element, instead of breaking the flow of the content. Note: An inline element does not start on a new line and only takes up as much width as necessary.
The class name is used as a selector in HTML which helps to give some value to the element attributes. The document. getElementById() method is used to return the element in the document with the “id” attribute and the “className” attribute can be used to change/append the class of the element.
An inline CSS is used to apply a unique style to a single HTML element. An inline CSS uses the style attribute of an HTML element.
You need to use className
.
Try:
div[0].className = "tagging";
If you want to add tha class to the existing one you can use:
div[0].className += " tagging"; // adding white-space is important
Demo here
To read: MDN className.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With