how i can create a
javascript
code to add class name to specific divs only for Exapmle : i want to add a class_name to from div5 to the end of all divs ?
Asked
Active
Viewed 134 times
1

Muhammed Anwar
- 21
- 4
-
Please, include your code on the question – reisdev Jul 17 '18 at 21:48
-
`Content`? – Ryan Morton Jul 17 '18 at 21:57
3 Answers
0
function applyClass(elem_position, tagname, classname)
{
var div_elems = document.querySelectorAll(tagname);
for (var i = elem_position-1; i < div_elems.length;i++)
{
div_elems[i].className=classname;
}
}
Usage
Applies class some_class
to div
elements starting from position 3
applyClass(3,'div','some_class');

Erisan Olasheni
- 2,395
- 17
- 20
0
try this
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
</script>
</body>
</html>

George C.
- 6,574
- 12
- 55
- 80
0
If you're looking to add a class name from one div to others, I would recommend using JQuery. This can be done like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function changeColor(){
$( document ).ready(function() {
$("div").addClass("work");
});
}
</script>
<style>
.work {
color: red
}
</style>
<div style="width: 100%" class="work"><h1>Hello</h1></div>
<div style="width: 100%" class=""><h1>Hello</h1></div>
<button onclick="changeColor()">Change second color by inserting class!</button>

Novuw
- 31
- 5
-
i wanna add the class work to a num of divs except the first 4divs – Muhammed Anwar Jul 17 '18 at 21:58
-
I would recommend giving each div you want to add the class to a class of some sort, then in the jquery, just use $('.classname').addClass(); – Novuw Jul 17 '18 at 22:00
-
unfortunately i wanna make it dynamic so if more divs add to the container >js could handle it directly – Muhammed Anwar Jul 17 '18 at 22:05
-
Just put all the divs you want to add the class to in another div. Hardcode the class into the first div. Problem solved! – Novuw Jul 17 '18 at 22:16