Reputation: 4031
I am using getElementsByClassName
to fund multiple elements and change their style but as I found out getElementsByClassName
is not cross-browser compatible. Can you please help me to simplifie this code. I would prefer a native JS implementation but jQuery will be probably better so it is also fine....
So how can I then loop through the elements an depending on individual class change some style....
var ele = document.getElementsByClassName("dhSliderMobile");
for (var i = 0; i < ele.length; i++) {
if (ele[i].style.display === "block") {
ele[i].style.display = "none";
var div = document.getElementsByClassName("dhImageInfoDiv");
var div1 = document.getElementsByClassName("dhSeriesInfoDiv");
for (var j = 0; j < div.length; j++) {
div[j].style.right = 0 + "px";
div1[j].style.right = 0 + "px";
}
}
else {
ele[i].style.display = "block";
var div = document.getElementsByClassName("dhImageInfoDiv");
var div1 = document.getElementsByClassName("dhSeriesInfoDiv");
for (var j = 0; j < div.length; j++) {
div[j].style.right = 40 + "px";
div1[j].style.right = 40 + "px";
}
}
}
var ele = document.getElementsByClassName("dhSliderDesktop");
for (var i = 0; i < ele.length; i++) {
if (ele[i].style.display === "block") {
ele[i].style.display = "none";
var div = document.getElementsByClassName("dhImageInfoDiv");
var div1 = document.getElementsByClassName("dhSeriesInfoDiv");
for (var j = 0; j < div.length; j++) {
div[j].style.right = 0 + "px";
div1[j].style.right = 0 + "px";
}
}
else {
ele[i].style.display = "block";
var div = document.getElementsByClassName("dhImageInfoDiv");
var div1 = document.getElementsByClassName("dhSeriesInfoDiv");
for (var j = 0; j < div.length; j++) {
div[j].style.right = 20 + "px";
div1[j].style.right = 20 + "px";
}
}
}
Upvotes: 1
Views: 1480
Reputation: 8545
I think, your code will be like that with jQuery
$('.dhSliderMobile').toggle(function() {
if ($(this).is('visible')) { // if is visible
$('.dhImageInfoDiv, .dhSeriesInfoDiv').css('right', '40px');
return false; // then set invisible
}else{
$('.dhImageInfoDiv, .dhSeriesInfoDiv').css('right', 0);
return true; // set visible
}
});
Upvotes: 0
Reputation: 1261
To do CSS changes with jQuery its like that. You can also use event handlers if they meet the conditions of your counter to do some stuff. Anyways this will point you in the right way (I hope)
$('.dhImageInfoDiv, .dhSeriesInfoDiv').css({
'margin-left':'40px',
'display':'block'
})
Kind regards, M
Upvotes: 0
Reputation: 15861
try like this, class selector can be used via .
read here more : Class Selector
var multipleClassresults= $('.yourClass1, .yourClass2');
var singleClassResults= $('.yourClass1');
if you want to loop the results then do like this
$.each(multipleClassresults,function(index, item){
if($(item).hasClass('yourClassToCheck'))
{
//then do some styling
}
});
Upvotes: 2