Is it possible to use addEventListner in this way?

0

I'm studying javascript and decided to play around with the creation of fields with DOM CORE .

This is the code I've done so far:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<label for="telefone">Telefone:</label>
<input type="text" name="telefone" id="telefone">
<button id="submit">+</button>
<div class="n_campos"></div>

<script>

    document.querySelector('#submit').addEventListener('click', function(e){

        e.preventDefault();

        let n_telefone = document.createElement('label');
        let text = document.createTextNode('Telefone:');

        n_telefone.appendChild(text);

        let i_telefone = document.createElement('input');
        i_telefone.setAttribute('type', 'text');
        i_telefone.setAttribute('name', 'telefone');

        let buttonRemove = document.createElement('button');
        text = document.createTextNode('X');
        buttonRemove.appendChild(text);
        buttonRemove.setAttribute('id', 'remover');

        document.querySelector('.n_campos').appendChild(n_telefone);
        document.querySelector('.n_campos').appendChild(i_telefone);
        document.querySelector('.n_campos').appendChild(buttonRemove);   

    });

    document.querySelector('#remover').addEventListener('click', function(){
        console.log('removido');
    }); 

</script>

Field creation is working normally, however I'm trying to remove the created field in a way I do not know if it's possible. As you can see here:

let buttonRemove = document.createElement('button');
text = document.createTextNode('X');
buttonRemove.appendChild(text);
buttonRemove.setAttribute('id', 'remover');

I am assigning a #remover id to the button and when it is clicked it is called another addEventListner to remove it, but I hit 2 problems first when I call addEventListner as below, the id #remover has not yet been created and I am returned that the property does not exist, then when I add a new field and there is now the id #remover , it does not seem to me to be "removed."

I know I can remove the fields by just setting the onclick attribute on the button and calling a buttonRemove.setAttribute('onclick', 'algumafuncao()') function, however I wanted to know if it is possible in the way I mentioned above.

    
asked by anonymous 11.12.2017 / 01:40

1 answer

2

Well, the problem is that you are registering document.querySelector('#remover').addEventListener('click', before it exists.

It would be best if you put this event handset together when the button was created. Instead of

buttonRemove.setAttribute('id', 'remover');

use

buttonRemove.addEventListener('click', ...

So you're sure it's the right thing to do, and you just record the event handset once.

    
11.12.2017 / 07:32