How can I check whether element exists based on the classname? - javascript

As I mentioned in the title of my question, my element doesn't have id attribute. So how can I check whether it exists or not?
Here is my HTML:
<div class="classname">something</div>
Note1: I can do that if there is a id attribute like this:
var el = document.getElementById("idname");
if ( el ){
console.log("exists");
} else {
console.log("not");
}
But I want to know how can I do that based on the class name .. is it possible?
Note2: I use jQuery.

Vanilla javascript (without jQuery or any other lib):
var els = document.getElementsByClassName('className')
var first = els[0]
Notice that this is an array, since there could be many elements with that class
With jQuery:
var els = $('.className')
this will result in a jQuery object instead of a DOM element, so you better use the length() method for checking existence.

check with .length ,coz className will give you array list if exist
var el = document.getElementsByClassName("classname");
if ( el.length > 0 ){
console.log("exists");
} else {
console.log("not");
}

You need to use getElementsByClassName instead of getElementById.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
If using jQuery, please use class selector.
https://api.jquery.com/class-selector/

Try this:
if($('.classname').length > 0)
{
alert('exist');
}

You could try something like this:
if ($(".classname")[0]){ // do stuff }
This will use the jquery selector to grab all items with that class name, and attempt to access the first result (in position 0). This will fail if there are no elements with this class name.

You can use this:
var el = document.getElementsByClassName("classname");
if (el) {
console.log("exists");
} else {
console.log("not");
}

try this.this will show how to get the class in automatically document.ready or , when a button clicked.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="classname">something</div>
</body>
<script type="text/javascript">
// you can check the class name in document ready or in any other event like click
//this will show all the class names of div when document ready.
$(document).ready(function(){
var the_class_name = $("div").attr('class');
alert(the_class_name); // this put to show you the classs names
if(the_class_name == "classneme")
{
//do your coding
}
else
{
//do your coding
}
});
//if you want to get the class name when a button click and check if the class is exist
$(document).ready(function(){
$("div").click(function(){
var classnames = $(this).attr('class');
alert(classnames);
if (classnames == "your_class_name")
{
// your code here
}
else
{
// your code here
}
});
});
</script>
</html>

Related

How to check if a HTML element contains an other one?

I want to check if my title <h3> has the class highlight so I founded How to check if element contains specific class attribute but I'm not sure about how to fit it to my use case because it's not the <h3> which contains the class but the span inside it:
I tried to do this code:
$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});
but I got an error with the actual code:
imports/ui/layout.js:42:13: Unexpected token (42:13)
and it's the line String classes = obj.getAttribute("class");
Could someone help me to make it works ?
[EDIT] with the help of your answer I'm now here:
'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},
and it works so thank you everybody
I hope it will help you
$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
**can you just help me to do the action only on the clicked h3?**
If `click` action:
$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...
The above Code can also be written as follows:
$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
A rough way to know if you don't know have child selector
$('#nameMachine *').hasClass('yourClass'); // either true or false
Since you are using jquery, how about this simple solution:
$('.liContainer div h3 .highlight').removeClass('highlight');
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
You may try something like:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
Or a more specific version:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
Please note that the second css selector is to determine the scope of searching the first css selector.
find() will be searching in all of child element . So if there have wanted class its length will be 1 else length is 0.
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
This will do. hasClass documentation is here
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}

Hide element which is not a certain class

I want to hide an element which is not a certain class via jQuerys not() :
Content 1
Content 2
<div class="post-item c_1"></div>
<div class="post-item c_2"></div>
and
var thisContent;
jQuery('.content-btn').click(function() {
thisContent = this.id;
jQuery('.post_item').not('.'+thisContent).fadeOut();
}
am I using .not() method wrong in this context, because it seems not to work!
Your selector needs to be
jQuery('.post-item')
And you need to close the ) at the end of your jQuery, like this:
var thisContent;
jQuery('.content-btn').click(function() {
thisContent = this.id;
jQuery('.post-item').not('.'+thisContent).fadeOut();
});
See http://codepen.io/anon/pen/EaNXjg for a working example.
Try using
$(element).hasClass(".clasname").fadeOut();
as #AND Finally noticed modify your selector .. and while you use click on Anchor you need to use e.preventDefault; try this
jQuery('.content-btn').click(function(e) {
e.preventDefault;
thisContent = this.id;
jQuery('.post-item').not('.'+thisContent).fadeOut();
$('.'+thisContent).fadeIn();
});
DEMO

jQuery if Element has an ID?

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

How to add class to element only if it already does not have it?

How to add a class to an element only if it already does not have it? Say we don't know if the element has class="desired_class ... but we want to make sure it has.
Also, you can use classList property and it's add() method:
var element = document.getElementById('myElement');
element.classList.add('myClass');
The class name will be added only if the element does not have it.
More about classList:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
try this
var elem = $('selector');
if(!elem.hasClass('desired_class')){
elem.addClass('desired_class');
}
I wrote a JavaScript-only function that checks if the class exists before adding it to the element. (You can always use classList as mentioned here, but support for that starts with IE10.)
function addClass(name, element) {
var classesString;
classesString = element.className || "";
if (classesString.indexOf(name) === -1) {
element.className += " " + name;
}
}
var element = document.getElementById('some-element');
addClass("on", element); // Adds the class 'on'
addClass("on", element); // Ignored
addClass("on", element); // Ignored
document.write('Element classes: ' + element.className);
<div id="some-element"></div>
In plain javascript check class existence by using below code. Here I'm checking el (element) has tempClass or not
var el = document.getElementById("div1");
...
if (el.classList.contains("tempClass")){
return true;
}
if ($('element').hasClass('some_class')) {
$('element').addClass('class_name');
}
Are you sure you want to do it with JQuery only? You can do it with simple JavaScript
document.getElementById("elementId").getAttribute("class")
will give you null if the class attribute is not present.
if (!$("your_element").hasClass("desired_class")) {
$("your_element").addClass("desired_class");
}
An updated answer to this question is using toggleClass
$( "element" ).toggleClass( "className" );
http://api.jquery.com/toggleclass/

Why is my element null?

Why when I do an alert of the value (see below) it returns null? When an element with that ID exists?
// make reference to divs
var countdown_timer = document.getElementById("countdown_timer");
var countdown_image = document.getElementById("countdown_image");
// For element manipulation
if (type == 'image') {
var element = countdown_image;
} else if (type == 'timer') {
var element = countdown_timer;
}
alert(countdown_timer);
The div is as below..
<div class="timer" id="countdown_timer"></div>
It's possible that the javascript is being executed before the elements on your page are not loaded, thus the selector isn't finding anything. Is your javascript above the <body> tag? Try putting it after </body> and see how that works for you.
Another solution is to do:
window.onload = function () {
//put all your JS here
}
onload = function() {
// put you code here
}
Your call to document.getElementById needs to be after the markup for the div.
<div class="timer" id="countdown_timer"></div>
<script type="text/javascript">
var countdown_timer = document.getElementById("countdown_timer");
...
</script>
Alternatively, you could use the window.onload event, which would be the better way to go.

Categories

Resources