Personally my problem is a bit difficult for me to explain. I have these buttons
which are added every time when the "+" is clicked and when you click any of these button
they remove the div
pai% ( .list-group-item
).
The question is that I can only assign this function to these buttons directly in the html element ( onclick="removeField("+amntFileds+")"
) but I wanted something like:
document.querySelector(".remove-button").onclick=function(){...}
Unfortunately I can not do this because the buttons are added dynamically, and before adding them, they still do not exist by returning the selector error that does not find it. I'm trying to use this code in an extension to Chrome , and can not use inline code ...
Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, the hash ('sha256 -...'), or a nonce ('nonce -...') is required to enable inline execution.
JS:
var amntFileds = 1;
var superObj = document.querySelector(".list-group");
var btnAdd = document.querySelector(".add-button");
btnAdd.onclick = function(){
Element.prototype.setAttributes = function(attrs){
for (var index in attrs){
if ((index == 'styles' || index == 'style') && typeof attrs[index] == 'object'){
for (var prop in attrs[index]){
this.style[prop] = attrs[index][prop];
}
}else if (index == 'html'){
this.innerHTML = attrs[index]
}else{
this.setAttribute(index, attrs[index]);
}
}
};
//Criando o elementos;
var subObj = document.createElement("a");
var inputRemove = document.createElement("button");
//----------------Setando atributos dinamicamente-----------------\
//Definindo atributos ao subObj(div list-group-item):
subObj.setAttributes({
"id" : "sub-field"+amntFileds,
"class" : "list-group-item"
});
//Definindo atributos ao inputRemove(Botão de exclusão de comandos)
inputRemove.setAttributes({
"type" : "button",
"class" : "remove-button",
"html" : "✘",
//"onclick" : "removeField("+amntFileds+")"
});
//-----------------------------------------------------------------\
//Inserindo o elementos no subObj(list-group-item):
subObj.appendChild(inputRemove);
superObj.appendChild(subObj);
amntFileds++;
}
function removeField(id){
//Recebendo id de campo clicado
var subObj = document.querySelector("#sub-field"+id);
//Removendo o DIV com id específico do nó-pai:
var removed = superObj.removeChild(subObj);
//Decrementando campo adicionado em 1;
amntFileds--;
console.log("Campo "+amntFileds+" removido!");
}
HTML:
<div class="list-group">
</div>
<br><button type="button" class="add-button">✚</button><br>
<script type="text/javascript" src="action.js"></script>