CSS and JavaScript are different in many ways, almost all of which are too obvious to mention. However, one difference between the two bears explanation, because it is often the cause of confusion and consternation, especially among those who are making the transition from CSS guru to jQuery novice. In fact, it was one of the first things I asked about on the jQuery mailing list back in 2006. Since then, I've seen at least one question on the subject every week, and sometimes as many as one per day—despite an FAQ page and thesethreeplugins to help users deal with it.
How CSS and JavaScript Are Different
So, what's this important difference?
In CSS, style rules are automatically applied to any element that matches the selectors, no matter when those elements are added to the document (DOM).
In JavaScript, event handlers that are registered for elements in the document apply only to those elements that are part of the DOM at the time the event is attached. If we add similar elements to the DOM at a later time, whether through simple DOM manipulation or ajax, CSS will give those elements the same appearance, but JavaScript will not automatically make them act the same way.
For example, let's say we have "<button class="alert">Alert!</button>" in our document, and we want to attach a click handler to it that generates an alert message. In jQuery, we might do so with the following code:
[js]$(document).ready(function() {
$('button.alert').click(function() {
alert('this is an alert message');
});
});[/js]
Here we are registering the click handler for the button with a class of "alert" as soon as the DOM has loaded. So, the button is there, and we have a click function bound to it. If we add a second <button class="alert"> later on, however, it will know nothing about that click handler. The click event had been dealt with before this second button existed. So, the second button will not generate an alert.
Let's test what we've just discussed. I've added a script with the above three lines of jQuery code so that the following button will produce an alert message when clicked. Try it:
Events Don't Work with Added Elements
Now, let's create a new button (if we don't already have a second one) using jQuery code like this:
[js]$('#create-button').click(function() {
if ( $('button.alert').length < 2) {
$('