开发者

jQuery - checking existence of elements

开发者 https://www.devze.com 2022-12-21 06:44 出处:网络
Ok so basically I need to check,whether in my menu #Container exist any third level elements (h3 to be exact) and if yes give them some attribute. If not give this attribute to second level element (h

Ok so basically I need to check,whether in my menu #Container exist any third level elements (h3 to be exact) and if yes give them some attribute. If not give this attribute to second level element (h2) wh开发者_StackOverflowich always exists. Is :

if ($('h3')) {
  //some attribute
} else {
 //some attribute
};

the right method ?


Use .length for this, it's 0/false if there aren't any matches:

if ($('h3').length) {
 //some attribute
} else {
 //some attribute
};

Short version, less readable:

$($('h3').length ? 'h3' : 'h2').addClass("bob");


.....

if ($('#Container h3').length) {
  //some attribute
} else {
 //some attribute
};


Check the length of the returned jQuery object

if ($('h3').length != 0)) {
    $('h3').attr(...);
}
else {
    $('h2').attr(...);
}


To make it more readable, I offer this tweak:

var h3ElementsExist = $('h3').length
if (h3ElementsExist) {
  //some attribute
} else {
 //some attribute
};


I just realized an answer I posted to this feature a simple way to add a jQuery plugin for this was deleted a long time ago. Why? I don't know.

In conclusion, ele.length is simple, but not really elegant when you consider the fundamental flaws. It doesn't maintain jQuery style markup which could damage readability as well as forcing this in a "if" statement when this really "appears" like something jQuery should handle "naturally". Thus it does. If all your doing is seeking to apply an "attribute" to an exist element, you can simply make the call, with no if statement. If the element exist, it will get the new attribute. If it doesn't exist, it won't hurt anything or do anything other than continue on.

For example:

$('#Container h3').css('background', 'red');

This will make any existing H3 tags within an element id'd as Container have a red background, if they exist. If they don't exist, this code will, essentially, be ignored. However, if you wanted to do more, and maintain jQuery "chainability" as well as maintain jQuery style markup, then I would suggest a plugin I wrote that adds $.exist() to jQuery.

It allows for a variety of ways to call with a parameter for callbacks as well. Simply put, you can use it in an if statement such as if ($('h3').exist() { or you can create a 1 to 2 callback methods. The callback methods are pure and simple. If only 1 is supplied, (or simply the first callback method) it is the "exist" callback method. In other words, if the element exist, it will fire, and then return the element(s) thus maintaining jQuery "chainability". However, if it doesn't exist, nothing will happen, unless there is a second callback method provided. Then it will fire your second callback method, much like the "else" of the aforementioned if statement.

Some examples here:

$('#Container h3').exist(function(boolTrue, elements, indexPerEach) { /* DO WORK */ });

of with 2 callbacks

$('#Container h3').exist(function(boolTrue, elements, indexPerEach) { /* DO WORK */ },
function(boolFalse, elements) { /* Elements did NOT EXIST - DO WORK */ });

See more example and get minified version of plugin HERE

/*---PULIGIN---*/
;;(function($){$.exist||($.extend({exist:function(){var a,c,d;if(arguments.length)for(x in arguments)switch(typeof arguments[x]){case "function":"undefined"==typeof c?c=arguments[x]:d=arguments[x];break;case "object":if(arguments[x]instanceof jQuery)a=arguments[x];else{var b=arguments[x];for(y in b)"function"==typeof b[y]&&("undefined"==typeof c?c=b[y]:d=b[y]),"object"==typeof b[y]&&b[y]instanceof jQuery&&(a=b[y]),"string"==typeof b[y]&&(a=$(b[y]))}break;case "string":a=$(arguments[x])}if("function"==typeof c){var e=0<a.length?!0:!1;if(e)return a.each(function(b){c.apply(this,[e,a,b])});if("function"==typeof d)return d.apply(a,[e,a]),a}return 1>=a.length?0<a.length?!0:!1:a.length}}),$.fn.extend({exist:function(){var a=[$(this)];if(arguments.length)for(x in arguments)a.push(arguments[x]);return $.exist.apply($,a)}}))})(jQuery);
/*---PULIGIN---*/

See more info posted about it on another answer HERE


Check the size or length of the returned jQuery object

if ($('h3').size() != 0)) {
    $('h3').attr(...);
}
else {
    $('h2').attr(...);
}

or

if ($('h3').length != 0)) {
    $('h3').attr(...);
}
else {
    $('h2').attr(...);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消