jQuery: Check if div with certain class name exists - javascript

Using jQuery I'm programmatically generating a bunch of div's like this:
<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>
Somewhere else in my code I need to detect if these DIVs exist. The class name for the divs is the same but the ID changes for each div. Any idea how to detect them using jQuery?

You can simplify this by checking the first object that is returned from JQuery like so:
if ($(".mydivclass")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
In this case if there is a truthy value at the first ([0]) index, then assume class exists.
Edit 04/10/2013: I've created a jsperf test case here.

You can use size(), but jQuery recommends you use length to avoid the overhead of another function call:
$('div.mydivclass').length
So:
// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {
http://api.jquery.com/size/
http://api.jquery.com/length/
UPDATE
The selected answer uses a perf test, but it's slightly flawed since it is also including element selection as part of the perf, which is not what's being tested here. Here is an updated perf test:
http://jsperf.com/check-if-div-exists/3
My first run of the test shows that property retrieval is faster than index retrieval, although IMO it's pretty negligible. I still prefer using length as to me it makes more sense as to the intent of the code instead of a more terse condition.

Without jQuery:
Native JavaScript is always going to be faster. In this case: (example)
if (document.querySelector('.mydivclass') !== null) {
// .. it exists
}
If you want to check to see if a parent element contains another element with a specific class, you could use either of the following. (example)
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it exists as a child
}
Alternatively, you can use the .contains() method on the parent element. (example)
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it exists as a child
}
..and finally, if you want to check to see if a given element merely contains a certain class, use:
if (el.classList.contains(className)) {
// .. el contains the class
}

$('div').hasClass('mydivclass')// Returns true if the class exist.

Here is a solution without using Jquery
var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
// Class exists
}
reference link

It's quite simple...
if ($('.mydivclass').length > 0) {
//do something
}

To test for div elements explicitly:
if( $('div.mydivclass').length ){...}

Here are some ways:
1. if($("div").hasClass("mydivclass")){
//Your code
//It returns true if any div has 'mydivclass' name. It is a based on the class name
}
2. if($("#myid1").hasClass("mydivclass")){
//Your code
// It returns true if specific div(myid1) has this class "mydivclass" name.
// It is a based on the specific div id's.
}
3. if($("div[class='mydivclass']").length > 0){
//Your code
// It returns all the divs whose class name is "mydivclass"
// and it's length would be greater than one.
}
We can use any one of the abobe defined ways based on the requirement.

The simple code is given below :
if ($('.mydivclass').length > 0) {
//Things to do if class exist
}
To hide the div with particuler id :
if ($('#'+given_id+'.mydivclass').length > 0) {
//Things to do if class exist
}

Best way is to check the length of the class as shown below:
if ($('.myDivClass').length) {

if ($("#myid1").hasClass("mydivclass")){// Do any thing}

Use this to search whole page
if($('*').hasClass('mydivclass')){
// Do Stuff
}

Here is very sample solution for check class (hasClass) in Javascript:
const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
// do something if 'hasClass' is exist.
}

In Jquery you can use like this.
if ($(".className")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
With JavaScript
if (document.getElementsByClassName("className").length > 0) {
// Do something if class exists
}else{
// Do something if class does not exist......
}

check if the div exists with a certain class
if ($(".mydivclass").length > 0) //it exists
{
}

if($(".myClass")[0] != undefined){
// it exists
}else{
// does not exist
}

The best way in Javascript:
if (document.getElementsByClassName("search-box").length > 0) {
// do something
}

if ($(".mydivclass").size()){
// code here
}
The size() method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass. If it returns 0, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.

var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}

Related

javascript switch statement, if string contains substring

I'm trying to figure out how to do a switch statement where I need to find a class name of the object, then do something depending on the class name (in the switch statement).
In this example, I need the switch statement to do whatever I need when the class contains a specific word, such as "person".
html
<div class="person temp something"></div>
javascript
$(document).on('mousedown', function(e) {
var clicked = $(e.target).attr('class');
console.log(clicked);
switch (clicked) {
case "person":
//do something
break;
default:
//do something
}
});
It's not guaranteed that the switch statement name, such as "person" will be in the first spot.
I know I can search through an array for a specific word, but I don't know how to add that to this sort of thing.
As I said in my comment, a switch statement doesn't appear the appropriate approach in this situation.
Since you are using jQuery, just use .hasClass:
if ($(e.target).hasClass('person')) {
// do something
}
If you want to do something more complicated for multiple classes, you can create a class -> function mapping and simply iterate over the class list:
var classActions = {
person: function(element) { /* do something */ },
temp: function(element) { /* do something */},
// ...
};
var classes = e.target.className.split(/\s+/);
$.each(classes, function(index, cls) {
classActions[cls](e.target);
});
You'll want to use a combination of .split() and .indexOf(). Your code would be something like this:
var clicked = $(e.target).attr('class');
var classes = clicked.split(' ');
if(classess.indexOf('person') > 0) {
//do work
} else if (classes.indexOf('foo') > 0) {
//do work
} else if (classes.indexOf('bar') > 0) {
//do work
}
MDN documentation on .split()
MDN documentation on .indexOf()
Note that there are plenty of methods that allow you to do this. For example you can use string.search(substring) to check if a string contains your substring. If there is a substring it returns the index it was found (some number from 0 to n), otherwise if it's not found it returns -1. So if the search is larger or equal to 0, the substring exist.
if(clicked.search("person") >= 0)
// "person" is in clicked

Automate Parent hierarchy

var classFind= $('.frame').parent().parent().parent().parent().parent();
if (classfind.hasClass(".class")) {
return true;
}
I have a class that is located according to this path^... How could I loop through the dom to automate this process with better code readability? If it does not find the .hasclass before it hits a null then simply return false.
Can't you just replace this with...
return !!$('.frame').closest('.class').length;
The closest methods travels up the DOM tree until it finds the element that matches the selector given as its param - and then stops immediately; it will return empty collection of elements (which is still an object, hence its length should be checked) if no such element is found. And !! is the same as Boolean() call - it's not required, but will make your function return boolean values (true/false) instead of 0/1.
You can try someting like this:
var classFind= $('.frame').closest(".class");
With the closest function, you will not get exact 5 parents, if it is what you want...
This selector will do this.
function findEl() {
if($('.class > * > * > * > * > .frame').length > 0) {
return true;
}
return false;
}
Test it on:
http://jsfiddle.net/S5juG/1/
Take a look at the child selector:
http://api.jquery.com/child-selector/

Return "True" on Empty jQuery Selector Array?

I'm working on creating a more semantic way of checking for elements with jQuery. Using $("#element").length > 0 just doesn't really feel very well worded to me, so I'm making my own selector addition for use in .is:
if($("#element").is(":present")) {
console.log("It's aliiiveeee!!");
}
That part was easy, like this:
$.extend($.expr[':'],{
present: function(a) {
return $(a).length > 0;
}
});
I want to go a step further, and make it easy to see if an element doesn't exist, using similar syntax:
$.extend($.expr[':'],{
present: function(a) {
return $(a).length > 0;
},
absent: function(a) {
return $(a).length === 0;
}
});
$(function() {
if($("#element").is(":absent")) {
console.log("He's dead, Jim.");
}
});
But this part is surprisingly hard to do. I think it's because I'm paring down the returned elements to get a result, and paring the selector to .length === 0 is the same as asking for no elelements: it returns false no matter what.
I've tried a lot of different ways to reverse things and get this to return true when the element doesn't exist, and false if it does:
return $(a).length === 0;
return !($(a).length > 0);
if(!($(a).length > 0)) {
return true;
}
if($(a).length > 0) {
return false;
} else {
return true;
}
return !!($(a).length === 0);
// etc...
Is there an easy way to get this to just return true if the element doesn't exist, and false if it does?
The definition of is:
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.
The problem is that since you have no elements, it's not possible that one of your elements matches some condition. jQuery is not even calling your code because there are no elements.
EDIT: To clarify slightly, your code is being called once for every element in your object (at least until one returns true). No elements means the code is never called. a in your code is always a single element.
EDIT2: With that in mind, this would be a more efficient implementation of present:
$.extend($.expr[':'],{
present: function(a) {
return true;
}
});
You can simply use
if(​$('element').length) // 1 or 0 will be returned
or
$.extend($.expr[':'],{
present: function(a) {
return $(a).length;
}
});
if($('#element').is(':present'))
{
// code for existence
}
else
{
// code for non-existence
}
Example.
Given that $().is() won't even run when the collection is empty, the :present selector is rather superfluous. So rather than playing with $.expr[':'], I'd go with extending $.fn to contain appropriate function, e.g.:
$.fn.extend({
hasAny: function() {
return this.length > 0;
},
});
or
$.fn.extend({
isEmpty: function() {
return this.length == 0;
},
});
The reason I would personally go with this approach is that selectors are typically used to check particular properties of elements (compare :checked, :enabled, :selected, :hover, etc.), not the properties of jQuery element set as a whole (e.g. .size(), .index()).
Usage would of course be similar to the following:
if ($('#element').isEmpty())
console.log("He's dead, Jim.");
0 is "falsy" in JavaScript.
You can just return !$(a).length.
How about:
if ( !$(a)[0] ) {
// $(a) is empty
}
So, $(a)[0] retrieves the first element in the jQuery object. If that element is null/undefined, that means that the jQuery object is empty.

Jquery search througha class check if it has a certain id

hey I want to search through a class and check if that class contains a certain id. Do I have to use .each? if i do i dont know how to exactly use it, could someone show me how to use it in this context,
any help is appreciated
if(id == $('.people').attr('id'))
{
alert("person exists");
}
since ids should not be used more than once, you simply can do:
if($('#' + id + '.people').length >= 1)
alert('person exists');
You can search for an ID with
$('#my-id')
In your case,
$('#' + id)
You can check if the result is empty by testing for length:
if($('#'+id).length == 0)
To verify that it is a .person element that has the given ID, you could test
if($('.person#'+id).length > 0) {
alert('person exists');
}
Since an id can only be used once you can instead search for the element with that id and check if it has the class. That will be much faster:
$('#the-id').hasClass('the-class');
One solution would be to use a simple selector, and check if that element exists.
if ($('.people#'+id).length()) { //Checking length() checks if element exists
alert("person exists");
}

jquery, how to check if a specific ID is a child of an other id?

I have a specific id ("mysubid"), now I want to check if this element (this id) is in a child path of an other id ("mymainid").
Is there an easy way to do this or will I go upwards, element by element, to see if the element is in a child path.
By child path I am talking about something like this:
A > B > C > D
So D is in the Child Path of A,B and C
You all are making this very complicated. Use the descendant selector:
if ($('#mymainid #mysubid').length) {
// #mysubid is inside #mymainid
}
var isInPath = $("#mysubid").closest("#mymainid").length > 0;
if( $("#mymainid").find("#mysubid").length > 0 )
if($('#mysubid','#mymainid').length)
{
}
This will check to see if #mysubid is within #mymainid
jQuery( selector, [ context ] )
selector: A string containing a selector expression
context: A DOM Element, Document, or jQuery to use as context
This is a just an overlaod for $('#mymainid').find('#mysubid').lentgh btw, verified from: http://github.com/jquery/jquery/blob/master/src/core.js#L162
On another note, using a method such as $('#a #b') resorts to using the Sizzle Selector witch is slower than doing $('#a',$('#b')), witch uses purely javascript's getElementById
Note: as jQuery returns an empty object by default if the selection is not found you should always use length.
If you want to see the entire chain as an array use elm.parentNode and work backwards. So, to answer your question (and the depth or distance between the elements) in POJ, you can use:
var doc = document,
child = doc.getElementById("mysubid"),
parent = doc.getElementById("mymainid"),
getParents = function (elm) {
var a = [], p = elm.parentNode;
while (p) {
a.push(p);
p = p.parentNode;
}
return a;
};
getParents(child).indexOf(parent);
I tried on various browsers and the DOM function below is between 3 to 10 times faster than the selector methods(jQuery or document.querySelectorAll)
function is(parent){
return {
aParentOf:function(child){
var cp = child.parentNode;
if(cp){
return cp.id === parent.id ?
true : is(parent).aParentOf(cp);
}
}
}
}
The call below will return true if A is a parent of D
is(document.getElementById('A')).aParentOf(document.getElementById('D'))
For just few calls I would use the $('#A #D').length
For very frequent calls I would use the DOM one.
Using the 'is' method actually returns a boolean.
if($('#mymainid').is(':has(#mysubid)')) // true
Going the other direction...
if($('#mysubid').parents('#mymainid').length) // 1

Categories

Resources