How can I detect if a selector returns null?

0 votes

What is the best way to detect if a jQuery-selector returns an empty object. If you do:

alert($('#notAnElement'));

you get [object Object], so the way I do it now is:

alert($('#notAnElement').get(0));

which will write "undefined", and so you can do a check for that. But it seems very bad. What other way is there?

Oct 4 in JQuery by kartik
• 36,020 points
67 views

1 answer to this question.

0 votes

Hello @kartik,

My favourite is to extend jQuery with this tiny convenience:

$.fn.exists = function () {
    return this.length !== 0;
}

Used like:

$("#notAnElement").exists();

More explicit than using length.

Hope it helps!!
Thank you!!

answered Oct 4 by Niroj
• 78,480 points

Related Questions In JQuery

0 votes
1 answer

How can I convert a DOM element to a jQuery element?

Hello, Use this: var elm = document.createElement("div"); var jelm = ...READ MORE

answered 2 days ago in JQuery by Niroj
• 78,480 points
3 views
0 votes
1 answer

How can selector expression to not select elements with a specific class?

Hello @kartik, You need the :not() selector: $('div[cla ...READ MORE

answered 1 day ago in JQuery by Niroj
• 78,480 points
4 views
0 votes
1 answer

How can I implement my own $(document).ready functionality without using jQuery?

Hello @kartik,  There are three options: If script is the last ...READ MORE

answered Apr 28 in JQuery by Niroj
• 78,480 points
181 views
0 votes
1 answer

How to check if a jQuery plugin is loaded?

Hello @kartik, for the plugins that doesn't use ...READ MORE

answered Apr 28 in JQuery by Niroj
• 78,480 points
178 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 78,480 points
3,526 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 78,480 points
421 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 78,480 points
292 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 78,480 points
4,228 views
0 votes
1 answer

How can I refresh a page with jQuery?

Hello @kartik, Use location.reload(): $('#something').click(function() { location.reload(); }); The reload() function ...READ MORE

answered Sep 10 in JQuery by Niroj
• 78,480 points
34 views
0 votes
1 answer

How can I determine the direction of a jQuery scroll event?

Hello @kartik, Check current scrollTop vs previous scrollTop var lastScrollTop = 0; $(window).scroll(function(event){ ...READ MORE

answered 3 days ago in JQuery by Niroj
• 78,480 points
5 views