JavaScript add class to element

JavaScript add class to element 

Step 1: Create HTML file name is index.html

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Mycodehub - javascript add class to element</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<div class="wrap">
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
    
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
  
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
	<code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
    
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
  
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
	<code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
    
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
  
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
	<code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
    
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>
  
    <code>
     &lt;code&gt; This is some code.&lt;/code&gt;
    </code>


</div>
<!-- partial -->
  <script  src="./script.js"></script>

</body>
</html>

Step 2 : Create JavaScript file name is script.js

 

var body = document.body;

body.classList.add("MyClass");

Step 3 : create style file name is style.css

body {
  font: 12px Monaco, Consolas, "Lucida Console", monospace;
  background:#fff;
  -webkit-font-smoothing: antialiased;
  padding-top:30px;
  overflow:hidden;
}
.wrap {
  position:relative;
  background: #eee;
  margin: 0 auto;
  margin-bottom:20px;
  padding: 40px 10px 10px 90px;
  max-width:500px;
  color:#7b7b7b;
}
.wrap:before {
  content: "javascript add class to element - mycodshub.com";
  position: absolute;
  top: 0;
  left:0;
  font: 14px "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-weight: bold;
  color:#fff;
  background:#1e2629;
  width:100%;
  padding:5px 10px;
  box-sizing:border-box;
}
code {
  white-space:no-wrap;
  word-break: break-all;
  word-wrap: break-word;
  display:block;
  margin:6px 0;
  color:#af7aa5;
}

Related post : 

Document getelementsbyname

Element.classList

Leave a Comment