Home > Web Front-end > JS Tutorial > body text

Summary of three methods to set element class in js_javascript skills

WBOY
Release: 2016-05-16 18:02:59
Original
1259 people have browsed it
1. el.setAttribute('class','abc');
Copy code The code is as follows:





< title>setAttribute('class', 'abc')



test div

<script> <br>var div = document.getElementById('d1'); <br>div.setAttribute("class", "abc"); <br></script>

< /HTML>

IE6/7: The background color of the div is not red
IE8/9/10/Firefox/Safari/Chrome/Opera: The background color of the div is red
Result: IE6/ 7 does not support the setAttribute('class',xxx) method to set the class of an element.
2. el.setAttribute('className', 'abc')
Copy code Code As follows:





setAttribute('className', 'abc')



test div

<script> <br>var div = document.getElementById('d1'); <br>div.setAttribute("className", "abc"); <br></script>



IE6/7: The background color of the div is red
IE8/9/10/Firefox/Safari/Chrome/Opera: The background color of the div is not red
Result: IE8/9/10/Firefox/Safari/Chrome/Opera does not support the setAttribute('className',xxx) method to set the class of an element.
It’s interesting that when using setAttribute, the first parameters are class and className. The situation is exactly the opposite in IE6/7 and IE8/9/10/Firefox/Safari/Chrome/Opera.
3. el.className = 'abc';
Copy code The code is as follows:





el.className = 'abc'