What is the difference between following different ways of jQuery selections. To me they seem to be different ways of doing same thing with same performance costs:
$("#list li").hover(function () {
$(this).addClass("red");
}, function (){
$(this).removeClass("red");
});
With a greater than symbol:
$("#list > li").hover(function () {
$(this).addClass("red");
}, function (){
$(this).removeClass("red");
});
Add now with context:
$("li", $("#list")).hover(function () {
$(this).addClass("red");
}, function (){
$(this).removeClass("red");
});
#list lifinds the same set of elements, but in a modern browser it can pass the whole selector to the browser’s selector engine so it might be much faster.#list > lifinds alllielements that are immediate children of#list, i.e.<ul id="list"><li>but not<div id="list"><ul><li>.$("li", $("#list"))creates a jQuery object containing the element matching#listand then creates a new element containing anylielements with the context#list, i.e. alllielements that are inside#list. It is not really readable so don’t use that.There are also other ways:
$('#list').children('li')equals$('#list > li')$('#list').find('li')equals$('#list li')Both cases cannot use the speed advantages of a native
querySelectorAllso besides being more readable they are about as bad as$("li", $("#list"))