How to Add Classes to Existing WordPress Elements with JavaScript

You may need to add a new “class” to an element in WordPress. However, many of the code snippets on the web simply don’t work!

Alas, your search is over. The following is a foolproof way to add a new class to any element, for which you already have a unique Element ID.

Simply drop this code snippet into the post/page in question from within the TEXT editor (not the visual editor):

<script>
jQuery(document).ready(function() {
    mykey = document.getElementById('YOUR_UNIQUE_ID');
    jQuery(mykey).addClass("CLASSTOADD");
});
</script>

My preference is to add this script at the very bottom of the editor, below all other post/page content.

You should already have jQuery imported, but in case you don’t – you can add this extra line of code just above the opening: <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js”> </script>

In this case, your entire code block will look as follows:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script>
<script>
jQuery(document).ready(function() {
    mykey = document.getElementById('YOUR_UNIQUE_ID');
    jQuery(mykey).addClass("CLASSTOADD");
});
</script>

If you run into any issues or have questions, please feel free to let me know.