Henk Z Henk Z - 1 month ago 4x
Javascript Question

jQuery add class not working well

For some reason my code is not working, because it is not adding a class.

I want to add a class when clicking on the

and when clicking again it should be removed. When clicking again it should be added and so on.

What am I missing?


<a class="show-specs" id="displayText" href="javascript:toggle();">Show specs</a>


<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
.addClass( "left-float" );
text.innerHTML = "Show specs";
else {
ele.style.display = "block";
text.innerHTML = "Hide specs";


You need to add a selector before a jQuery method like so:

$("#displayText").addClass( "left-float" );

The string "#displayText" means to select the element with the id "#displayText".

Although there is a better way to do this in jQuery by using .toggleClass() such as:

$("#displayText").click(function() {


Since you are using jQuery to attach an event handler replace the href with #:

<a class="show-specs" id="displayText" href="#">Show specs</a>