Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why class attribute cannot assign inline by javascript? [duplicate]

Tags:

javascript

css

<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>
like image 778
dramasea Avatar asked Sep 05 '13 05:09

dramasea


People also ask

What are inline tags in HTML?

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.

How do you change the class style of an element?

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.

What is inline in CSS?

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.


2 Answers

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.

like image 56
Sergio Avatar answered Oct 12 '22 02:10

Sergio


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

like image 39
Sudhir Bastakoti Avatar answered Oct 12 '22 02:10

Sudhir Bastakoti