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.
$(document). ready(function() { if ($('#DivID'). length){ alert('Found with Length'); } if ($('#DivID'). length > 0 ) { alert('Found with Length bigger then Zero'); } if ($('#DivID') !=
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With