1

我如何创建javascript代码以仅针对 Exapmle 将类名添加到特定 div:我想将class_name添加到从 div5 到所有 div 的末尾?

4

3 回答 3

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;
    }
}

用法

将类应用于some_classdiv位置 3 开始的元素

applyClass(3,'div','some_class');
于 2018-07-17T21:51:14.943 回答
0

尝试这个

<!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>
于 2018-07-17T21:54:44.070 回答
0

如果您希望将一个 div 中的类名添加到其他 div,我建议您使用 JQuery。这可以这样做:

<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>

于 2018-07-17T21:55:45.057 回答