html - Comment puis-je changer un élément paramètre#39;s class avec JavaScript

Mots clés : javascripthtmldomjavascript

meilleur 5 Réponses html - Comment puis-je changer un élément paramètre#39;s class avec JavaScript

vote vote

99

document.getElementById("MyElement").classList.add('MyClass');  document.getElementById("MyElement").classList.remove('MyClass');  if ( document.getElementById("MyElement").classList.contains('MyClass') )  document.getElementById("MyElement").classList.toggle('MyClass'); 
document.getElementById("MyElement").className = "MyClass"; 
document.getElementById("MyElement").className += " MyClass"; 
document.getElementById("MyElement").className =    document.getElementById("MyElement").className.replace       ( /(?:^|\s)MyClass(?!\S)/g , '' ) /* Code wrapped for readability - above is all one statement */ 
(?:^|\s) # Match the start of the string or any single whitespace character  MyClass  # The literal text for the classname to remove  (?!\S)   # Negative lookahead to verify the above is the whole classname          # Ensures there is no non-space character following          # (i.e. must be the end of the string or space) 
if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) ) 
<script type="text/javascript">     function changeClass(){         // Code examples from above     } </script> ... <button onclick="changeClass()">My Button</button> 
<script type="text/javascript">     function changeClass(){         // Code examples from above     }      window.onload = function(){         document.getElementById("MyElement").addEventListener( 'click', changeClass);     } </script> ... <button id="MyElement">My Button</button> 
$('#MyElement').addClass('MyClass');  $('#MyElement').removeClass('MyClass');  if ( $('#MyElement').hasClass('MyClass') ) 
$('#MyElement').toggleClass('MyClass'); 
$('#MyElement').click(changeClass); 
$(':button:contains(My Button)').click(changeClass); 
vote vote

86

document.getElementById('id').classList.add('class'); document.getElementById('id').classList.remove('class'); 
document.getElementById('id').classList.toggle('class'); 
vote vote

78

function hasClass(ele, cls) {     return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }  function addClass(ele, cls) {     if (!hasClass(ele, cls))         ele.className += " " + cls; }  function removeClass(ele, cls) {     if (hasClass(ele, cls)) {         var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');         ele.className = ele.className.replace(reg, ' ');     } } 
<script type="text/javascript">     function changeClass(btn, cls) {         if(!hasClass(btn, cls)) {             addClass(btn, cls);         }     } </script> ... <button onclick="changeClass(this, "someClass")">My Button</button> 
vote vote

66

document.getElementById('foo').className = 'bar'; 
vote vote

55

<div class="firstClass" onclick="this.className='secondClass'"> 

Questions similaires