Add id to dynamically created DIV

2.3k views Asked by At

I would like to add an ID to the div with the class name="leaflet-control-layers-base". Because this HTML script is automatically generated through an API (Leaflet) when the page is loaded, I cannot add the id within the script.

The reason I am asking is because I have two of these scripts as shown below within my page. I would like to distinct them from each other so that I can refer to them individually. The only difference is that the other script is not located in the "TOCContent" div.

Any ideas how I can add an id using JavaScript or jQuery to the 'leaflet-control-layers-base' class?

Here is my script:

<div id="TOCContent">
    <div class="leaflet-control-layers leaflet-control-layers-expanded" aria-haspopup="true">
        <form class="leaflet-control-layers-list">
            <div class="leaflet-control-layers-base">
        </form>
</div>

2

There are 2 answers

0
Rayon On

Try this:

$(".leaflet-control-layers-base").attr("id","your id will go here");
1
MrCode On

Select the element using the combinator selector, to ensure it selects a descendant of #TOCContent, then set the id property.

$('#TOCContent .leaflet-control-layers-base').prop('id', 'someid');

Remember to run this after your API code has rendered the elements on the page, not before. You will probably need to hook up to some sort of complete event on your API, because the basic DOM Ready event will likely fire before the API has rendered the elements.


Side note: it may not be necessary to give the element an ID, since by doing so you need to obtain a reference to the element anyway, which you can store in a variable.

var base = $('#TOCContent .leaflet-control-layers-base');