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

后端 未结 3 1789
庸人自扰
庸人自扰 2021-01-15 03:15

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

相关标签:
3条回答
  • 2021-01-15 03:48

    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.
    });
    
    0 讨论(0)
  • 2021-01-15 03:50

    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;
    });
    
    0 讨论(0)
  • 2021-01-15 03:56

    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());
    }
    
    0 讨论(0)
提交回复
热议问题