Cloudboy22
Cloudboy22

Reputation: 1514

How can you grab elements in dom and apply different css without id?

I am bit confused here. I am working on a dynamic project and I want to apply different css to divs which have same class but no id. How can I apply different css say to first div with same class, and then different css to second div of same class and so on... Let's say I have fullwidthContainer class applied to 3 divs For the first div, I want width 1000px, to the second I want 800px and so on. I can not give an id or another class here since it's dynamically generated. Please help.

Thanks.

Ok i did this using javascript

  function emphatic()
{
    var totalContainers=document.getElementsByClassName('fullwidthContainer')
    var className=1;

    for (var i = 0; i < totalContainers.length; i++) {
        className=className+1;
        totalContainers[i].setAttribute("class", "dropdown_5columns fullwidthContainer customMenuClass");
    };

}
emphatic();

Now how do i append classname with 1 added everytime to the new class. i mean something like customclass1, customclass2 and so on to divs.. thanks,

Upvotes: 5

Views: 70

Answers (2)

user4164128
user4164128

Reputation:

Maybe you're aslo interested in a pure javascript solution.

var divs = document.getElementsByClassName('myClass');
var width = [100,200,300];
for(var i=0;i<divs.length;i++) {
    divs[i].style.width = width[i] + 'px';
    // increases classname by i
    divs[i].className = 'myClass anotherClass' + i;
}

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

Perhaps you can use the element indexes although it's not entirely clear if you have relationships to match:

Example using increments based on index:

$('.someClass').each(function(index){
  $(this).width( 300 * (index+1) );
});

Example using array:

var widths =[ 600, 900, 500];

$('.someClass').each(function(index){
  $(this).width( widths[index] );
});

Array version could also be adapted to add classes.

Index starts at zero being first matching element in page

Upvotes: 4

Related Questions