jQuery how to get complete class name with hasClass - javascript

I want to check the complete class name using hasClass() function in jQuery. I have class named "Disclaimer"
<div id="fakeform1">
<div class="Disclaimer"> I want to get complete class name
</div></div>
<script>
$(document).ready(function({
if($('#fakeform1').hasClass('sclaimer')==0) {
alert(COMPLETE CLASS NAME);
}
));
</script>
How I get the complete name of sclaimer class which is Disclaimer ?

you can't use hasClass for that case, try this:
if ($('#fakeform1').attr('class').indexOf('sclaimer') !== -1) {
alert($('#fakeform1').attr('class'));
}
EDIT:
Looks like I misunderstand your question, if you want to check the children element, then try this one:
var test = $('#fakeform1').find('div').filter(function() { return $(this).attr('class').indexOf('sclaimer') !== -1; });
if (test.length) {
alert(test.attr('class'));
}
fiddle: https://jsfiddle.net/zjq5u2vL/

Related

click anywhere except a specified class

I need to show an alert if there is a click anywhere except on .m1wrap div.
Why this doesn't work? Alert appears even if I click on .m1wrap
$(document).on("click", function(e) {
if (e.target.class !== "m1wrap") {
alert ("323");
};
})
In e.target there is no property class (it returns undefined), you can use property e.target.className (Note it returns all classes from class attribute), however in jQuery there is method .hasClass .
Also you can use classList with .contains method e.target.classList.contains('m1wrap')
$(document).on('click', function (e) {
if (!$(e.target).hasClass('m1wrap')) {
console.log('not m1wrap');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m1wrap">m1wrap</div>
<p>test</p>
You need to use className to address the class attribute.
So either use jQuery's hasClass() or vanilla JS className.
Note: This example using className is only checking if the class does not equal "m1wrap", rather than does not contain "m1wrap".
$(document).on("click", function(e) {
if (e.target.className !== "m1wrap") {
alert ("323");
};
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m0wrap">m0wrap</div>
<div class="m1wrap">m1wrap</div>
<div class="m2wrap">m2wrap</div>
There is no class in e.target, only className is available.
Code snippets:
$(document).on("click", function (e) {
if (e.target.className !== "m1wrap") {
alert("323");
};
})
But the following code snippets is the best way if there is multiple class names for an element.
$(document).on("click", function (e) {
if (!$(e.target).hasClass('m1wrap')) {
alert("323");
};
})
Event.target returns Element, which has not class property.
So you can use className property or getAttribute() method to get Element's class name.
If you want to use jQuery API, you can use hasClass() method
Try this,
<div>
<div class="m1wrap">
Non Clickable area
</div>
Clickable area
Clickable area
Clickable areaClickable areaClickable
Clickable areaClickable
Clickable area
</div>
JS
$(('body')).on('click',function(e) {
if ($(e.target).hasClass('m1wrap')) {
return false;
}
alert("hello");
})
DEMO

Change an ID upon click

I know how to change a class name with another class upon click, but not sure how to do so when using id instead.
Below is how the class is setup:
<script>
$(function(){
$(".collapseArrow").click(function(){
$(".collapseArrow").removeClass("collapseArrow")
$(this).addClass("collapseArrowUp")
return false;
})
})
</script>
The reason for that is that the class is already being used and i have to use the id to style it instead.
Plain Javascript approach:-
This approach takes advantage of the this keyword as follows...
HTML:
<div id="oldId" onclick="changeId(this)"></div>
JS:
function changeId(element) {
element.id = "someNewId";
}
or simply (in one line) as part of the HTML
<div id="oldId" onclick="this.id='someNewId';"></div>
jQuery approach:-
Use the attr() function as follows...
$(function(){
$("#oldId").click(function(){
$("#oldId").attr("id","newId");
return false;
});
});
EDIT: As requested, I will give a piece of code to toggle between 2 ids.
HTML:
<div id="firstId" onclick="toggleId(this)"></div>
JS:
function toggleId(element) {
if(element.id == "firstId") {
element.id = "secondId";
} else { //This will only execute when element.id == "secondId"
element.id = "firstId";
}
}
You can use the attr() function
<script>
$(function(){
$("#collapseArrow").click(function(){
$("#collapseArrow").attr('id',"collapseArrowUp");
return false;
});
});
</script>
Instead of changing the id, do it with multiple classes.
This could help you...
$(function(){
$(".collapseArrow").click(function(){
$(".collapseArrow").removeClass("up")
$(this).addClass("up")
return false;
})
})
You can use
$(this).attr("id"',"new id");
But i would use classes and add important to override existing css rules
Hope i helped
i have to use the id to style it instead.
I suggest you not to do this because in the dom structure ids have most preference against the class names. So this would be little difficult to override the styles which have been applied with the ids.
Instead i would recommend to use classes instead:
$(function() {
$(".collapseArrow").click(function() {
$(this).toggleClass("collapseArrow collapseArrowUp")
return false;
});
});
$(function() {
$(".collapseArrow").click(function() {
$(this).toggleClass("collapseArrow collapseArrowUp")
return false;
});
});
.collapseArrow::before {
content: "[-]"
}
.collapseArrowUp::before{
content: "[+]"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class='collapseArrow'></h1>
You should not change an id. If you need to use a different selector to select the same element, add another class to the element, e.g.
<span class="collapsArrow SomethingMeaningful"></span>
Then you just need to use a different selector method:
$( "span[class~='SomethingMeaningful']" )
.removeClass("collapseArrow")
.addClass("collapseArrowUp");
Then you can style the element with:
.SomethingMeaningful{
}

How to check already given class and add another one

recently I wrote one few lines of js in order to check the DOM structure and add "in" class in case user clicked on link. Now I need to use has property but I dont know how its used. Here is code:
$(document).on('click', '.collapse-all > a', function () {
var $collapseList = $(this).closest('#main-content').find('.collapse-list'),
$container = $collapseList.find('.collapse').removeAttr('style'),
$collapsed = $collapseList.find('.mehr-pfeil');
if ($container.filter('.in').length > 0) {
$container.removeClass('in');
} else {
$container.addClass('in');
}
});
$(function () {
$('.collapse-all > a').click();
});
// here is my try to check the DOM and add another class on <a> element
$(function () {
$container.hasClass('in') {
if ($container.filter('.in').length > 0) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
}
});
So right now everything worked but when I tried to check if js has gave in class to .collapse then my code breaks. Can anyone tell me where I've made mistake
hasClass() returns a bool so your function may check something like this
if($container.hasClass('in')) {
...
}
As noted by TheBlueAussie, your $container is also not in the scope of your ready function.
A quick fix would be to global the variable like so
var $container;
$(document).on('click', '.collapse-all > a', function () {
var $collapseList = $(this).closest('#main-content').find('.collapse-list'),
$collapsed = $collapseList.find('.mehr-pfeil');
$container = $collapseList.find('.collapse').removeAttr('style');
...
}
There are 2 problems in your code
1,$container is not in the scope of your class checking function.
2, The way you used hasClass method is wrong
It will return true or false. So you can check it inside an if condition.
var $collapseList = $(this).closest('#main-content').find('.collapse-list');
$container = $collapseList.find('.collapse');
if ($container.hasClass('in')) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
take a look at
.hasClass() to check if element has a class.
you can use it in a if and than addClass
if($('.class').hasClass('className'))
{
$('.class').addClass('xy');
//or
$('.class').removeClass('className');
//and so on
//.class could be #id as well
}
You should move the hasClass statement to a condition start since this method returns a boolean (true/false) value:
// here is my try to check the DOM and add another class on <a> element
$(function () {
if ($container.hasClass('in')) {
if ($container.filter('.in').length > 0) {
$collapsed.addClass('mehr-pfeil-active');
} else {
$collapsed.removeClass('mehr-pfeil-active');
}
}
});
You should also declare the $container variable inside this function or move its initialization to be a global one.
try this
$container.hasClass('in');
or if you want to toggle class
$container.toggleClass('in')

Jquery hasClass issue

im trying to check if one of the DIV's has class "visible" which is being add by a jquery plugin, it seems not to work.
it works when i check the first element, but if i want to check next div, it doenst finds it.
help is appreciated.
My DIV
<div class="swiper-slide welcome" id="welcome"></div>
2nd DIV
<div class="swiper-slide intro-early-life" id="intro-early-life"></div>
MY JQUERY
<script type="text/javascript">
$(document).ready(function() {
if ($('.welcome').hasClass('swiper-slide-visible')) {
alert("working");
}
});
</script>
Im not using same ID, maybe it was my bad explanation. I can use the class as well, no difference.
$(document).ready(function() {
if ($('#welcome').hasClass('swiper-slide') && $('#welcome').hasClass('visible')) {
alert("working");
}
});
if ($('#welcome').is(":visible") && $('#welcome').hasClass("swiper-slide")) {
alert("Yeah!");
}
Perhaps that would work better?
Edit: Also swiper-slide-visible class doesn't exist on the page - perhaps this is the issue...?
You can use also as
$(document).ready(function() {
if ($('#welcome').hasClasses(['swiper-slide', 'visible']);) {
alert("working");
}
});
$.fn.extend({
hasClasses: function (selectors) {
var self = this;
for (var i in selectors) {
if ($(self).hasClass(selectors[i]))
return true;
}
return false;
}
});
Use .is()
if ($('#welcome').is('.swiper-slide, .visible'){
Id Must Be unique you can use classes instaed
Two HTML elements with same id attribute: How bad is it really?
You could use .is() instead:
$(document).ready(function() {
if ($('.welcome').is('.swiper-slide.visible')) {
alert("working");
}
});

addClass function not worked using JQuery

I have the following code:
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".hideAccessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".hideAccessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
This script removes a class fine but it does not want to add the class. Can you see any issues with this code?
When you add hideAccessRequest class to the element, you search for it by the existence of that class.. if you are adding it, that class won't already be applied and thus you won't match any elements.
$(".hideAccessRequest") doesn't exist. you need to use id, I guess. And you might want to look at toggleClass.
you'd need an identifier for the classes you want to toggle ex:"accessRequest"... try this.
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".accessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".accessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
classes are space-delimited, so if you want them hidden by default...
<div class="accessRequest hideAccessRequest">...</div>

Categories