I’ve got a function that appends a
You can handle it in different ways,
Objective is to check if the div exist then execute the code. Simple.
Condition:
$('#myDiv').length
Note:
#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' >
This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below
// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax
if (document.getElementById(name)) {
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 1
if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 2
if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 3
if ($('#'+ name).length > 0 ) {
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 4
if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
if($("#id").length) /*exists*/
if(!$("#id").length) /*doesn't exist*/
The most simple way is..
if(window["myId"]){
// ..
}
This is also part of HTML5 specs: https://www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object
window[name]
Returns the indicated element or collection of elements.
Nick's answer nails it. You could also use the return value of getElementById directly as your condition, rather than comparing it to null (either way works, but I personally find this style a little more readable):
if (document.getElementById(name)) {
alert('this record already exists');
} else {
// do stuff
}
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
Use the first if condition for id and the 2nd one for class.
if ( $( "#myDiv" ).length ) {
//id id ( "#myDiv" ) is exist this will perform
$( "#myDiv" ).show();
}
Another shorthand way:
$( "#myDiv" ).length && $( "#myDiv" ).show();