Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use <a href="https://developer.mozilla.org/en-US/docs/DOM/element.classList" rel="noreferrer"><code>element.classList</code></a> <code>.contains</code> method:</p> <pre><code>element.classList.contains(class); </code></pre> <p>This works on all current browsers and there are polyfills to support older browsers too. </p> <hr> <p><strong>Alternatively</strong>, if you work with older browsers and don't want to use polyfills to fix them, using <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer"><code>indexOf</code></a> is correct, but you have to tweak it a little:</p> <pre><code>function hasClass(element, className) { return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') &gt; -1; } </code></pre> <p>Otherwise you will also get <code>true</code> if the class you are looking for is part of another class name.</p> <p><a href="http://jsfiddle.net/fkling/zBKCC/" rel="noreferrer"><strong>DEMO</strong></a></p> <p>jQuery uses a similar (if not the same) method.</p> <hr> <p><strong>Applied to the example:</strong></p> <p>As this does not work together with the switch statement, you could achieve the same effect with this code:</p> <pre><code>var test = document.getElementById("test"), classes = ['class1', 'class2', 'class3', 'class4']; test.innerHTML = ""; for(var i = 0, j = classes.length; i &lt; j; i++) { if(hasClass(test, classes[i])) { test.innerHTML = "I have " + classes[i]; break; } } </code></pre> <p>It's also less redundant ;)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload