Check If An Element Exists Using jQuery

Here are some examples on how to determine if an element is existing in your html page.

jQuery selector sample:

{code type=”javascript”}

if ($("yourElementSelector").length) {

//your script here

}

{/code}

jQuery selector sample 2:

{code type=”javascript”}

if (jQuery("yourElementSelector").length) {

//your script here

}

{/code}

{code type=”javascript”}

if ($(".elementClassName").length) {

//your script here

}

if ($("#elementIdName").length) {

//your script here

}

{/code}

HTML tag selector sample:

{code type=”javascript”}

if ($("ul").length) {

//your script here

}

if ($("ul").length) {

//your script here

}

{/code}

Check if element exists using plain javascript, select the element using itsid=”” attribute

{code type=”javascript”}

if (document.getElementById("elementId") != ‘undefined’) {

//your script here

}

{/code}

Hope this will be useful to anyone 🙂

Recommended Posts