SCcode SCcode - 16 days ago 6
CSS Question

Numbering Divs using javascript function

I've been trying to number my divs (1, 2, 3...) using javascript.

HTML:

<div id="anId(this)" class="nextClass"></div>


Javascript:

function anId(elementthis) {
var newId = 0;
elementthis.setAttribute("id", newId++);
}


How can I make this actually work?

Answer

You can wrap them in a parent div and then use a js script to run down the tree and number the div's.

The code would look something like this:

var app = function() {
    var wrapper = document.getElementById('wrapper').childNodes;
    var id = 0
    for (var i = 0; i < wrapper.length; i++) {
        if (wrapper[i].nodeName === "DIV") {
            wrapper[i].id = id;
            id += 1;
        }
    }
}();
Comments