Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How check for ID existence using jQuery?

People also ask

How do I check if an element ID exists?

Use the getElementById method to get an element by id if it exists, e.g. if (document. getElementById('my-id') !== null){} . The method returns the element whose id matches the provided string.

How do I check if a div exists?

$(document). ready(function() { if ($('#DivID'). length){ alert('Found with Length'); } if ($('#DivID'). length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') !=

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".

How can I get ID in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.


if ($('#input-name').length) {
  // do something
}

Check for .length or .size() on the object. The select won't fail, jQuery will always return an object.


In my test the assignment didn't cause an error, it simply returned undefined.

In which case the solution would be the following:

var name = $('#input-name').attr("value");
if (name) {
  // blah blah
}

Or maybe:

var name = $('#input-name').attr("value") || 'defaultValue';

... if that makes sense in your case.