This appears to be a simple issue, yet it is not functioning correctly.
I managed to make it work by placing the .normal class above the .highlight class, despite only adjusting the position and not altering the style. This lack of logic is puzzling.
Since I am unable to paste the HTML code here directly, I will need to provide it in sections. I have also included a snapshot of all the code.
Ensure that you start with an empty HTML page. The doctype does not seem to affect the outcome, as I have tested it with different doctypes without success.
The following code is within the style block after the header:
.highlight { color:black; background-color:yellow; }
.normal { color:white; background-color: blue; }
Following this, there is a script tag linking to the latest jQuery code at
Subsequently, there is a script block containing the following:
$(document).ready(function () {
$('#maindiv').css('cursor', 'pointer');
$('#maindiv').click(function () {
//alert("click");
// $(this).toggleClass("highlight"); //this does not work!
// $(this).addClass('highlight'); //this does not work!
// $(this).attr("class", "highlight"); //this works
// $(this).css("background", "yellow"); this works
// Using JavaScript directly also functions properly.
// var element = document.getElementById('maindiv');
// element.setAttribute("class", "highlight");
});
});
In the body, there is a p tag with an id name of "maindiv" and a class of "normal."
The text inside prompts to click here.
I am eager for someone else to attempt this as well. It seems peculiar, as all other methods are functional except for the .addClass and .toggleClass which do not behave correctly.
As a new user, I cannot attach the snapshot of the complete code here, but you can download it from: