Bo Cao
Bo Cao

Reputation: 101

JQuery - animate() color attribute only works for first tag?

Why is the following JQuery "color" effect only applied to the first p tag? The opacity effect works for all p tag. If I use $("p#jp_test"), it works for all p tag. I am confused.

$(document).ready(function(){
    $("#jq_test").animate({
        left: '50px',
        opacity:'0.5',
        color: '#FF0000'}, 2000);
});

Upvotes: 0

Views: 40

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

The problem is that you're using the same id on more than one element, which is invalid. Use a class instead.

The reason $("#jq_test") only does the first and $("p#jq_test") does all of them is that when jQuery sees a selector that's purely an id selector, it uses document.getElementById, which is very fast, and returns a single element. But if it sees a selector that's more complex, it uses querySelectorAll (or its own handling in Sizzle on really old browsers), which finds all of them. But that's unspecified behavior; using the same id on more than one element is, again, invalid and a browser could choose not to find those elements via querySelectorAll, too, if it wanted.

Upvotes: 3

Related Questions