Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery determining if element exists on page

How can I determine if an element exists on a page... for instance...

$('select[name="modifier_option"]')

If that select box exists on the screen I need to validate it's value on the page to ensure it's value is > 0, but if it doesn't exist I don't need to worry about it.

like image 855
Webnet Avatar asked Nov 23 '10 15:11

Webnet


People also ask

How do I check if an element ID exists?

Approach 1: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then compare the element (variable that store ID) with 'null' and identify whether the element exists or not.

How do you check class is exists in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".


2 Answers

    if( $('select[name="modifier_option"]').length )
{
     // it exists
}
like image 175
Shawn Avatar answered Oct 23 '22 05:10

Shawn


copy/paste from here: Is there an "exists" function for jQuery?

jQuery.fn.exists = function(){return jQuery(this).length>0;}

if ($(selector).exists()) {
    // Do something
}
like image 4
Silver Light Avatar answered Oct 23 '22 06:10

Silver Light