Meier Maxi
Meier Maxi

Reputation: 17

jQuery check before delete tag

Does it make sense to check for existing tag before doing something with it? Or is jQuery doing thing on the fly?

Here a samplecode

$('#my_ul li.active').removeClass('active');

or...

if(  $('#my_ul li.active').length ) {
    $('#my_ul li.active').removeClass('active');
}

Upvotes: 0

Views: 112

Answers (2)

Subtubes
Subtubes

Reputation: 16883

jQuery does a loop for every element returned by the selection. So if you have zero elements in an array then the looping occurs zero times. take this example

html

<ul>
   <li>Hello World</li>
</ul>

the JavaScript is

var $('li');

that will return an array of elements if you console log it it will look like this;

[<li>Hello world</li>]

since the above is an array when jQuery loops through it will do it once. However if the section returns zero items the loop will never occur there

$('div').removeClass(".myClass");

basically the removeClass plugin (it is a plugin by the way its just a plugin thats part of the core jQuery code)

the plugin will do something like this;

$.each($('div), function () {
  //some code to remove the class 
})

Hope this helps you understand the internals of jQuery

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382304

No it doesn't make sense. It's neither faster nor useful. Don't do it.

Simply do

 $('#my_ul li').removeClass('active');

and there won't be any error, even if there is no such element, and even if the li elements don't have the active class.

Upvotes: 3

Related Questions