This question already has answers here:
Is there an "exists" function for jQuery?
(47 answers)
Closed 8 years ago.
How do I check if an element exists if the element is created by .append() method?
$('elemId').length doesn't work for me.
$('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.
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
Try this:
if ($("#mydiv").length > 0){
// do something here
}
The length property will return zero if element does not exists.
How do I check if an element exists
if ($("#mydiv").length){ }
If it is 0, it will evaluate to false, anything more than that true.
There is no need for a greater than, less than comparison.
your elemId as its name suggests, is an Id attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}
You can also use array-like notation and check for the first element.
The first element of an empty array or collection is simply undefined, so you get the "normal" javascript truthy/falsy behaviour:
var el = $('body')[0];
if (el) {
console.log('element found', el);
}
if (!el) {
console.log('no element found');
}
You can use native JS to test for the existence of an object:
if (document.getElementById('elemId') instanceof Object){
// do something here
}
Don't forget, jQuery is nothing more than a sophisticated (and very useful) wrapper around native Javascript commands and properties
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
Related
I am trying to use javaScript to determine if an element with a specific class name exists on an html page. The element in question is only sometimes loaded on the page.
When I use document.getElementsByClassName('element-in-question').innerHTML = "Hello"
It will work when the element exists, but when it doesn't exist, it will return as "cannot set property of innerHTML of undefined and the rest of the code will not run.
Is there a way to check if an element exists, and only modify it when it does without breaking the rest of the code?
Thanks for the help
You can also use document.querySelector which will return the first element within the document if it exists, if not, it returns null.
const targetElement = document.querySelector('.element-in-question');
if (targetElement) {
targetElement.innerText = 'Hi there!';
}
<div class="element-in-question"></div>
Tip: If you're just adding text consider using innerText instead of innerHTML.
Just wrap you code with if statement :
const elemts = document.getElementsByClassName('element-in-question');
if(elemts.length) {
// this actually need to be elemts[0].innerHTML
elemts.innerHTML = "Hello"
}
Note: document.getElementsByClassName will return array/collection of elements so if you really know that there is no other elements keep using it otherwise switch to getElementById.
as per documentation:
The getElementsByClassName() method returns a collection of all
elements in the document with the specified class name, as an
HTMLCollection object.
It's very simple with the condition IF
If you want to get elements by class, the function will return an array (a collection of all elements in the document with the specified class name), so you will check as following :
if (document.getElementsByClassName('class-in-question').length > 0) {
// Existed
}
If you want to get an element by specified id, the function will return an objet HTML with that id, so you will check as following :
if (document.getElementById('id-in-question')) {
// Existed
}
I am trying to write a short script that looks to see if a class or id is present in then document. If it is then do the following:
$(".tab_item").removeClass("tab_item_color");
$(this).addClass("tab_item_color");
You can use the length property on a jQuery object. For example:
if( $('.your-class').length )
{
$(".tab_item").removeClass("tab_item_color");
}
The if() block will only execute if there is an element in the DOM which has a class of your-class.
You can also do this
$(function() {
if ($('.yourClassName').length){
$(".tab_item").removeClass("tab_item_color").addClass("YourNewClassName"); //It will swap your class.
}
});
For more information you can also visit .length
You can simplify this by checking the first object that is returned from jquery. For-example
if ($(".your-class")[0]){
$(".tab_item").removeClass("tab_item_color");
}
This question already has answers here:
Why does $('#id') return true if id doesn't exist?
(6 answers)
Closed 8 years ago.
I'm new to jQuery and I have the following misunderstanding.
<p>adasd</p>
<p>42323123</p>
...
$("p").eq(4).html("some html")
I know I have only two <p> in my HTML so I do expect that console will say me an exception or something that will signal me I'm doing the wrong thing.
console.log($("p").eq(4))
prints:
prevObject: jQuery.fn.init[2], context: document, jquery: "2.1.1", constructor: function, selector:...
Why is it working like that?
As the documentation page for jQuery's .eq() function states:
If an element cannot be found at the specified zero-based index, the method constructs a new jQuery object with an empty set and a length property of 0.
If you'd like to check whether $("p").eq(4) has successfully found an element, you can do something like this:
var paragraphFive = $("p").eq(4);
if (paragraphFive.length) {
// It exists
}
else {
// It doesn't
}
This (and many other selectors) will always return a jQuery object, regardless of whether the selector matched any elements. In the case that no elements are matched, the jQuery object returned will contain zero elements; you can test for this with .length:
console.log($("p").eq(4).length) // 0
Created this JsFiddle
HTML:
<p>first</p>
<p>second</p>
Script:
$(document).ready(function(){
window.console&&console.log($("p").length);
});
This will log '2'. You can always check if there is 4 elements in your array before reading it. This is good practice in ANY programming language BTW...
This happens because there is no 4th element to return. jQuery returns an empty set for your selection.
Try:
var el;
(el = $('p').eq(4)).length != 0 ?
el.html('some html') :
console.log('did nothing');
http://jsbin.com/dizem/1/edit
Clicking on an element:
$('.my_list').click(function(){
var selected_object = $(this);
$('.my_list').each(function(){
var current_object = $(this);
if( selected_object == current_object ) alert('FOUND IT !');
});
});
I don't know why, but I don't get the alert message "FOUND IT !".
You can use the jQuery.is function:
Check the current matched set of elements against a selector, element,
or jQuery object and return true if at least one of these elements
matches the given arguments.
if (selected_object.is(current_object)) {
...
}
An alternate solution is to use jQuery.get function to get the raw elements and compare them using == or === operator:
if (selected_object.get(0) == current_object.get(0)) {
...
}
jsFiddle demo
There's good answer provided... but it's important to understand, why you directly can't compare selectors in jQuery.
jQuery selectors return data structures which will never be equal in the sense of reference equality. So the only way to figure this out is to get DOM reference from the jQuery object and to compare DOM elements.
The simplest comparison of DOM reference for the above example would be:
selected_object.[0] == current_object.[0]
Right now I have a dynamic string that assigns it's values to a particular div class.
Output looks like this
<div class="12923"></div>
I want to find that 'randNumber' div, then check if it has another class 'x'
Currently what I have now doesn't work:
var randNumber = 12923
var lookingForYou = $$('.'+randNumber);
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$ returns an Elements instance, Elements is an array-like Class
anyway since you are basically filtering, you can tell Slick that you need an element with both class:
var randNumber = 12923;
if($$('.' + randNumber +'.XCLASS').length>0){
alert('XCLASS FOUND');
}else{
//dostuff
}
or you could just use one of the Elements methods, I think .some will be your best choice here:
var randNumber = 12923
var lookingForYou = $$('.' + randNumber);
alert(lookingForYou.some(function(el){
return el.hasClass('XCLASS');
}))
EDIT:
adding some links:
A better way to use Elements on MooTools blog
in my second example I used the some method, which, by looking at the source is not overloaded, but is just the one in Array.prototype.some:
Element.js source reference
Array.some on MDN
$$ returns an array of all matching elems. Not sure if you can do a hasclass on an array. Might have to do a .each() then do it. Try $('body').getElement('.'+randNumber).hasClass('XCLASS') this way you grab 1 elem if you don't want to mess with the array.
Here:
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$() returns an array, and hasClass() performs the check on each element of the array, returning an array of booleans. Unfortunately, when you check if (...), then the return array, even if all of the values are false, is evaluated as true because it's non-empty.