Jochen Schmidt
Jochen Schmidt

Reputation: 109

adding classes (serially numbered) to each DIV on page automatically via javascript?

i'm running a contact-form-plugin on my wordpress installation. everything works fine but i want to style my form a little bit more. to do it like this i have to style some DIVs (which the plugin is processing) in a different way. the problem is: all DIV-containers have no IDs or classes! everything is processed by the plugin and my PHP-skills are like zero so i have to deal with this "naked" DIVs ;-)

the question is: is it possible to add serially numbered classes to each DIV on the current site via javascript?

thanks so far and i hope you get waht i mean (sorry for that shitty english)!

Upvotes: 2

Views: 1028

Answers (3)

Felix Kling
Felix Kling

Reputation: 816364

Yet another way, passing a callback to .attr [docs]:

$('div').attr('class', function(i) {
    return 'someClass' + i;
});

Though you could also use this for IDs instead, since each class will be unique.

Note that you don't have to use IDs or classes to select elements, there are a number of selectors and traversal methods with which you can get a reference to the elements you want.


To prevent overriding existing classes, either select only the elements with no class or somehow narrow down the selection of divs to only those you want:

$('div:not([class])')

or use .addClass [docs] instead of .attr:

$('div').addClass(function(i) {
    return 'someClass' + i;
});

Upvotes: 3

Travis J
Travis J

Reputation: 82267

You could do this:

var divs = document.getElementsByTagName("div");
var className = "myClass";
for( var i = 0, max = divs.length; i< max; i++ ){
 divs[i].setAttribute("class",className + i.toString());
}

Upvotes: 1

Adil
Adil

Reputation: 148110

You need something like this,

Live Demo

$('div').each(function(i, item){
    $(this).attr('class', "YourClass" + i); //You can replace i with some other variable if required and increment it.
});

Upvotes: 1

Related Questions