简体   繁体   中英

How to set id/class when I have an unkown number of divs

Depending on how many rows my sql query returns I will create divs to present the data.

Every div needs to have an unique id but I do not know how to do this efficiently.

Right now I have defined a couple of id's but this can't possibly be the right way to do it.

#myid1, #myid2, #myid3, myid4 { }

This will not work if I get more rows.

What is the best/correct way to do this?

You could use this CSS selector to select any div element with an ID that starts with 'myid':

div[id^="myid"] { ... }

If you want to automatically assign unique ID's to your elements, you could use JavaScript (nodeList is an array of your elements)

Ancient JS:

for (var i = 0; i < nodeList.length; i++) { //loop through every element in your array
    nodeList[i].id = 'myid' + i; //set element ID to 'myid' + current index
}

ES6:

nodeList.forEach((item, i) => { //loop through every element in your array
    item.id = 'myid' + i; //set element ID to 'myid' + current index
});

Your generated ID's will be 'myid0', 'myid1', 'myid2' and so on.

you can use the "class" instead of "ID" beacuse you dont know how much row is there.when you have to apply same css on more than one element than you have to use "class".

you can also use id and class aplly id on parent div and class on sub div.

like

#row_container .row{
}

here #row_container is parent div and .row is child div

if you don't want to apply a css on that row than simply you have to genrate dayanmic id's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM