JQuery: How to check if two elements have the same class
Is there a way to check if two elements have the same class name? My code looks like this ...
<body class="foo bar cats">
<a href="#" class="foo">Link</a>
<a href="#" class="puppies">Link</a>
What I want to do is add another class to the link foo
if it matches the class in the body. How can I check if one of the classes in my references matches the class in the body using jQuery?
source to share
I would suggest:
$('a').each(
function() {
var classes = this.classList;
for (var i=0,len=classes.length; i<len; i++){
if ($('body').hasClass(classes[i])){
$(this).addClass('bodySharesClass');
}
}
});
Edited to try and use the Internet Explorer account to understand / use / implement .classList
:
if (!document.createElement().classList){
var useAttr = true;
}
$('a').each(
function(i) {
var classes = [];
if (!useAttr){
classes = this.classList;
}
else {
classes = $(this).attr('class');
}
for (var i=0,len=classes.length; i<len; i++){
if ($('body').hasClass(classes[i])){
$(this).addClass('bodySharesClass');
}
}
});
Edited because my previous attempt appears, for IE accounting, failed. Sigh. Still! This approach should work, although I can't test it as I don't have IE and Windows:
$('a').each(
function(i) {
var classes = this.className.split(/\s+/);
for (var i=0,len=classes.length; i<len; i++){
if ($('body').hasClass(classes[i])){
$(this).addClass('bodySharesClass');
}
}
});
Literature:
-
classList
... -
hasClass()
...
source to share
ok, assuming I understand you correctly, you can do something like this ...
var link = $(".foo");//or select your link another way
var linkClass = link.attr("class");
if($("body").hasClass(linkClass)){
//link has matching class
link.addClass("newClass");
}
As you can see, I used the hasClass () function of JQuery to check if the body tab has an appropriate class.
If your link will have more than one class name, you can do it like this:
var link = $(".foo");//or select your link another way
var linkClass = link.attr("class");
var classList = linkClass.split(/\s+/);
var matchFound = false;
for(var i = 0; i < classList.length; i++){
if($("body").hasClass(classList[i])){
//link has matching class
matchFound = true;
}
}
if(matchFound){
link.addClass("newClass");
}
Also, if you want to process all of your links at the same time, you can transfer the whole thing to JQuery's each () and change the first line like this ...
$("a").each(function(index){
var link = $(this);
//the rest of the above code here
});
source to share