I need another solution to make this code

Asked

Viewed 40 times

3

People I made a code to appear the word at the end with the click, but my code became very extensive. There’s some other way 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);

};

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 you want to have this feature (example below). You can also do it in other ways by filtering elements with a certain ID or part of an ID. But then the logic is the same: you add an event headphone to the element and the this within that function is the element clicked.

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: https://jsfiddle.net/su4kxrmz/

When you make changes like this, to avoid repeating code you say render the DRY code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.