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:
how can I make that?
This question is related to
php
javascript
jquery
html
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 isset(element) {
return element.length > 0;
}
Or, as a jQuery extension:
$.fn.exists = function() { return this.length > 0; };
// later ...
if ( $("#id").exists() ) {
// do something
}
You can use length
:
if($("#one").length) { // 0 == false; >0 == true
alert('yes');
}
function el(id) {
return document.getElementById(id);
}
if (el('one') || el('two') || el('three')) {
alert('yes');
} else if (el('four')) {
alert('no');
}
php.js ( http://www.phpjs.org/ ) has a isset()
function: http://phpjs.org/functions/isset:454
Source: Stackoverflow.com