I need another solution to make this code

3

People I made a code to appear the word at the end with the click, but my code was very extensive. Do you have any other solution to do the same thing?

<!DOCTYPE>
<html>
<head>
    <title>Substituir</title>
</head>
<body>

    <p id="nome1" onclick="nome1()">Dinossauro</p>
    <p id="nome2" onclick="nome2()">Tubarao</p>
    <p id="nome3" onclick="nome3()">Ornitorrinco</p>
    <p id="nome4" onclick="nome4()">Gralha</p>

    <p id="recebe"></p>

    <script src="teste.js"></script>
</body>
</html>

JS:

var botao = document.querySelector("p");

function nome1(){

    var selecionaTexto = document.querySelector("#nome1");
    var texto = selecionaTexto.textContent;

    var campoRecebe = document.querySelector("#recebe");
    campoRecebe.textContent = texto;

    console.log(texto);

};
function nome2(){

    var selecionaTexto = document.querySelector("#nome2");
    var texto = selecionaTexto.textContent;

    var campoRecebe = document.querySelector("#recebe");
    campoRecebe.textContent = texto;

    console.log(texto);

};
function nome3(){

    var selecionaTexto = document.querySelector("#nome3");
    var texto = selecionaTexto.textContent;

    var campoRecebe = document.querySelector("#recebe");
    campoRecebe.textContent = texto;

    console.log(texto);

};
function nome4(){

    var selecionaTexto = document.querySelector("#nome4");
    var texto = selecionaTexto.textContent;

    var campoRecebe = document.querySelector("#recebe");
    campoRecebe.textContent = texto;

    console.log(texto);

};
    
asked by anonymous 30.03.2016 / 21:25

1 answer

1

You can do this in a more organized way by looking for patterns in the code.

You can, for example, give the same class to all the elements that you want to have this functionality (example below). You can also do it in other ways, by filtering elements with a certain ID or part ID. But then the logic is the same: you add an event handset to the element and the this within that function is the clicked element.

var nomes = document.querySelectorAll('.nome');
for (var i = 0; i < nomes.length; i++) {
    nomes[i].addEventListener('click', buscarNome)
}

function buscarNome() {
    var texto = this.textContent;
    var campoRecebe = document.querySelector("#recebe");
    campoRecebe.textContent = texto;
    console.log(texto);
}

Example: link

When you make changes of this sort, to avoid repetition of code it is said make DRY code

    
30.03.2016 / 21:31