Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting DIVs without #id, Adding #id

I'm new to JavaScript and CSS and my skills are poor at best. I have an idea how to solve my problem but I don't have the knowledge to solve it.
I have a code like this:

<div class="detail">
    <div class="detail-group"></div>
    <div class="detail-group"></div>
    <div class="detail-group"></div>
</div> 

I have to append one existing DIV with unique #id to each one of the .detail-group DIVs. I have to specify the .detail-group even though they are exactly the same. I don't have access to the HTML to edit it manually.
If I'm correct my best shot is to use JS to set IDs to those .detail-group DIVs.
I used CSS to target each one of them with this and create a difference:

.detail-group:nth-child(1) { padding-right: 0.01px }
.detail-group:nth-child(2) { padding-right: 0.02px }
.detail-group:nth-child(3) { padding-right: 0.03px }

But I don't know how to detect this difference with JS and work with it. Is it possible to differentiate the order of elements in JS? If there is, How to do it. And how to add IDs to them?

A side note, I'm working with Enjin modules and thats why I don't have access to their HTML. If someone has experience in this field it will be greatly appreciated.

like image 472
Radoslav T. Avatar asked Aug 24 '15 13:08

Radoslav T.


1 Answers

You can use .attr() function along with its callback to set the ids using the index of div elements:

$('.detail-group').attr('id', function(i) {
  return 'detailgroup'+(i+1);
});

Working Demo

like image 99
Milind Anantwar Avatar answered Oct 13 '22 15:10

Milind Anantwar