isset in jQuery? [duplicate]
Possible Duplicate:
Finding whether the element exists in whole html page
i would like make somethings:
HTML:
<span id="one">one</span>
<span id="two">two</span>
<span id="three">three</span>
JavaScript:
if (isset($("#one"))){
alert('yes');
}
if (isset($("#two"))){
alert('yes');
}
if (isset($("#three"))){
alert('yes');
}
if (!isset($("#four"))){
alert('no');
}
LIVE:
http://jsfiddle.net/8KYxe/
how can I make that?
if (($("#one").length > 0)){
alert('yes');
}
if (($("#two").length > 0)){
alert('yes');
}
if (($("#three").length > 0)){
alert('yes');
}
if (($("#four")).length == 0){
alert('no');
}
This is what you need :)
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
function isset(element) {
return element.length > 0;
}
http://jsfiddle.net/8KYxe/1/
Or, as a jQuery extension:
$.fn.exists = function() { return this.length > 0; };
// later ...
if ( $("#id").exists() ) {
// do something
}
php.js ( http://www.phpjs.org/ ) has a isset()
function: http://phpjs.org/functions/isset:454
You can simply use this:
if ($("#one")){
alert('yes');
}
if ($("#two")){
alert('yes');
}
if ($("#three")){
alert('yes');
}
if ($("#four")){
alert('no');
}
Sorry, my mistake, it does not work.
function el(id) {
return document.getElementById(id);
}
if (el('one') || el('two') || el('three')) {
alert('yes');
} else if (el('four')) {
alert('no');
}
精彩评论