js 给某个或指定的div增加class 样式

js 给指定div增加class 样式

  • 第一、el.setAttribute('class','abc')
  • 第二、 el.setAttribute('className', 'abc')
  • 第三、el.className = 'abc'

第一、el.setAttribute(‘class’,‘abc’)

<!DOCTYPE HTML>
    <HTML>
    <HEAD>
    <meta charset="utf-8" />
    <title>setAttribute('class', 'abc')</title>
    <style type="text/css">
    .abc {
    background: red;
    }
    </style>
    </HEAD>
    <BODY>
    <div id="div">test div</div>
    <script>
    var div = document.getElementById('div');
    div.setAttribute("class", "abc");
    </script>
    </BODY>
    </HTML>

第二、 el.setAttribute(‘className’, ‘abc’)

<!DOCTYPE HTML>
    <HTML>
    <HEAD>
    <meta charset="utf-8" />
    <title>setAttribute('className', 'abc')</title>
    <style type="text/css">
    .abc {
    background: red;
    }
    </style>
    </HEAD>
    <BODY>
    <div id="div">test div</div>
    <script>
    var div = document.getElementById('div');
    div.setAttribute("className", "abc");
    </script>
    </BODY>
    </HTML>

第三、el.className = ‘abc’

<!DOCTYPE HTML>
    <HTML>
    <HEAD>
    <meta charset="utf-8" />
    <title>el.className = 'abc'</title>
    <style type="text/css">
    .abc {
    background: red;
    }
    </style>
    </HEAD>
    <BODY>
    <div id="div">test div</div>
    <script>
    var div = document.getElementById('div');
    div.className = 'abc';
    </script>
    </BODY>
    </HTML>

你可能感兴趣的:(Javascript)