Check if element exists in jQuery
$('elemId').length
doesn't work for
me.
You need to put #
before element id:
$('#elemId').length
---^
With vanilla JavaScript, you don't need the hash (#
) e.g. document.getElementById('id_here')
, however when using jQuery, you do need to put hash to target elements based on id
just like CSS.
Is there an exists function for jQuery?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0
means false
, everything else true
. So you could write:
if ($(selector).length)
You don't need that >0
part.
Do I really need to check if an element exists with jQuery?
One guy I work with says the correct way to check should be:
if ($( "#myDiv" ) && $( "#myDiv" ).length ) {
//do something
}
He's wrong, at least in terms of the $( "#myDiv" ) &&
part. jQuery's $(selector)
always returns an object, which by definition is truthy. So that part is pointless, and re-querying the DOM for no reason.
I mean from a performance or latency wise, do they perform the same?
Re-querying the DOM for no reason is a waste, but most of the time it doesn't matter in any observable way, and especially not for ID selectors like $("#myDiv")
which are optimized by jQuery into calls to getElementById
(which is blazingly-fast). So on the one hand, yes, it's wasteful extra work. On the other hand, browsers are so fast these days that you probably have bigger fish to fry. But it's probably extra pointless code, which is the larger issue.
To the general point: jQuery is set-based. This means that operations on sets with no elements in them are no-ops. E.g.:
$(".foo").addClass("bar");
...is a no-op (not an error) if no .foo
elements are in the DOM.
So check for length
if and when you care whether you matched elements. If you don't care and just want to perform operations on them if they're there, just go ahead and do the operation (with one important caveat1).
So basically, there are three scenarios:
You know the elements will be there, so the check is pointless
=> no checkYou don't know the elements will be there, but you don't care and just want to operate on them if they're there
=> no checkYou care whether the elements are there for some other reason
=> do the check
1 Here's the important caveat: If you're calling a jQuery function that returns something other than a jQuery object (for instance, val()
or offset()
or position()
, etc.), when you call it on an empty set, it will typically return undefined
(the exception is text()
, which will return ""
[text()
is not like the others in several ways; this is one of them]). So writing code that naively assumes those things will return what you're expecting, even when the set is empty, will bite you.
So for example:
if ($(".foo").offset().top > 20)
...will throw an error if there are no .foo
elements, because offset()
will return undefined
, not an object.
But this is fine:
$(".foo").closest(".bar").toggleClass("baz"):
...because even if there are no .foo
, closest()
will return another empty jQuery set, and calling toggleClass()
on it is a no-op.
So when dealing with an accessor that doesn't return a jQuery object, if you don't know for sure you're dealing with a set containing at least one element, you need more defensiveness, e.g.:
var offset = $(".foo").offset();
if (offset && offset.top > 20)
Again, most accessors (that don't return jQuery objects) do this, including val()
, offset()
, position()
, css()
, ...
jQuery - how to check if an element exists?
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}
Check if a div exists with jquery
The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.
jQuery determining if element exists on page
if( $('select[name="modifier_option"]').length )
{
// it exists
}
Check if a DIV element exists by its class in jQuery
You can look for the object and then check whether one was found:
if ($(".views-row-4").length) {
// at least one element with class "views-row-4"
}
jQuery: Checking if next element exists
Have you tried looking at .next('li').length
?
How to find if div with specific id exists in jQuery?
You can use .length
after the selector to see if it matched any elements, like this:
if($("#" + name).length == 0) {
//it doesn't exist
}
The full version:
$("li.friend").live('click', function(){
name = $(this).text();
if($("#" + name).length == 0) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
Or, the non-jQuery version for this part (since it's an ID):
$("li.friend").live('click', function(){
name = $(this).text();
if(document.getElementById(name) == null) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
Related Topics
Resize Cross Domain Iframe Height
How to Change Reactjs Styles Dynamically
Bootstrap Collapsed Menu Links Not Working on Mobile Devices
Set the Webkit-Keyframes From/To Parameter with JavaScript
Blinking/Flickering with Jqm and Phonegap on Android
How to Check Element's Visibility via JavaScript
Perspective Transform of Svg Paths (Four Corner Distort)
React - Prevent Event Trigger on Parent from Child
Jquery .Animate() Stop Scrolling When User Scrolls Manually
React Inline Style - Style Prop Expects a Mapping from Style Properties to Values, Not a String
Generating CSS Media Queries with JavaScript or Jquery
How to Change the Background Image of Div Using JavaScript
How to Animate the Drawing of Text on a Web Page
How to Play a Notification Sound on Websites
Fix First Column of a Bootstrap Table
"You May Need an Appropriate Loader to Handle This File Type" with Webpack and Babel