Radoslav T.
Radoslav T.

Reputation: 75

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.

Upvotes: 6

Views: 1826

Answers (2)

PeterKA
PeterKA

Reputation: 24638

You do not need to assign IDs to the divs in order to target them. Let's say the following variable shows - 'index of target div = index of element in array', 'ID of existing ID to append'

var ids = ['divid1','divid2','divid3'];

Then you can use the following code to append the div's with above IDs to the respective target DIVs:

$('.detail-group').append(function(i) {
    return $('#' + ids[i]);
    //or return $('#divid' + (i+1));
});

Alternatively, let's say you're able to select the existing DIVs via a common class say, .content-div, and divs represents these div's, then you could do it this way:

var divs = $('.content-div');
$('.detail-group').append(function(i) {
    return divs[i];
});

However, if you're adding the same div to all the three target DIVs consider removing the ID before so you don't end up with duplicate IDs:

//select the one DIV
var oneDiv = $('#oneDiv');
//detach it from DOM
oneDiv.detach();
//remove ID
oneDiv.removeAttr('id');
//clone oneDiv and add to the target DIVs
$('.detail-group').append(function() {
    return oneDiv.clone();
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

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

Upvotes: 11

Related Questions