I am trying to create a list of divs. When the new layer button is clicked, there is a new div created with a unique ID. When I try to call on these dynamically added divs, there is no response. I am confused because the preexisting divs work.
<input type="submit" id="newLayer" value="New Layer">
<div id="layersContainer" class="layerscontainer">
<div class="layer" id="layer1">fadfa</div>
<div class="layer" id="layer2">2</div>
</div>
var newLayerCounter = 2;
var layerID = "";
var layersArray = new Array();
var clickedElement = "";
function selectLayer(){
$(clickedElement).css({"background-color":"yellow"});
}
$('#layersContainer div').on("click", function(){
clickedElement = $(this).attr("id");
alert(clickedElement);
selectLayer();
});
$('#newLayer').on("click", function(){
newLayerCounter = newLayerCounter + 1;
layerID = "#layer"+ newLayerCounter;
$('<div/>', {
id: "layer"+ newLayerCounter,
class: "layer"
}).appendTo('#layersContainer');
$(layerID).text('hey');
})
Here is a link to a working JSfiddle