I want to remove a dynamically assigned class from an element but do not know the name of that class.
For example if I have:
<div id="myDiv" class="foo bar unknown"></div>
In this case the unknown class will always be in position 3.
How can I achieve this using Jquery?
function hideMyDiv(){
var rnd=Date.now();
$('#myDiv').addClass(rnd);
setTimeout(function(){
$('.'+rnd).hide();
},10000);
}
function overRide(){
$('#myDiv').3rdClass().remove();
}
You are doing something wrong here, order of classes shouldn't matter.
But anyway you can do this
var parts = $('#myDiv').attr('class').split(' ');
$('#myDiv').removeClass(parts[2]);
Try writing a small helper method that will take the DOM element.
function removeClass(elem) {
var c = elem.className.split(' '),
cName;
if (c && c.length > 0) {
cName = c.splice(0, c.length - 1);
elem.className = cName.join(' ');
}
};
You can always enforce the condition you want to use. Check Fiddle
Do this with jquery:
var _classes = $('a#somelink').attr('class').split(" ");
then you can loop thru that array and remove the one you want.
In one line
$('#myDiv').removeClass($('#myDiv').attr('class').split(' ')[2]);
Explained:
$('#myDiv') //jQuery selector
.removeClass //removed the named class
$('#myDiv') //jQuery selector
.attr('class') //get the class attribute of the element
.split(' ') //split it into an array, with the perpetrator being a blank space aka ' '
[2] //get the 3rd item in the array, remember it counts from 0, aka 0, 1, 2, 3, 4 ...
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.