I am trying to get the class name of each td
and then adding another class to each td
. For example: The current class is class = "X-marker"
and I want to add another class bgreen
and it should be class = "X-marker bgreen"
.
I used each
method to get the class name of each td
and then used attr
with each to set but it doesn't work. I don't get any error but it isn't working as expected.
The object is called winInfo
and the array variable is: winInfo.play = winArray[i];
var winInfo = checkWin();
if (winInfo.win) {
currentClass = $(winInfo.play).each(function () {
$(this).attr('class');
});
$(winInfo.play).each(function () {
$(this).attr('class', currentClass + ' bgreen');
});
}
It sounds like you're looking for addClass()
.
Might look something like this:
$(winInfo.play).addClass('bgreen');
As stated by @Hatchet, the method addClass
is clearly the easiest way to do it. However, and because it seems you are misunderstanding how each
works, here is how you could do this using each
and without addClass
.
I am assuming in the following that winInfo.play
is a proper dom selector (eg ".class-name p"
).
var winInfo = checkWin();
if (winInfo.win) {
// `each` is just a helper that will call the provided function
// for each of the object selected by jQuery (like a loop).
// It does not return any value.
$(winInfo.play).each(function () {
var currentClass = $(this).attr('class');
$(this).attr('class', currentClass + ' bgreen');
});
}
Oh, and because you might not need jQuery , here is how you would do it in plain js.
var winInfo = checkWin();
if (winInfo.win) {
// if winInfo.play is not a selector but a list of dom elements,
// just remove document.querySelectorAll.
for(var el of document.querySelectorAll(winInfo.play)){
el.classList.add('bggreen');
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.