3

Estoy intentando ver si es posible capturar el ID de un elemento (un DIV) que es padre de otros elementos (Span, IMg) , a traves del objeto generado por el addEventListener.

En mi codigo, me gustaria que cuando hago click sobre cualquier elemento, se modificase el texto por "IdDiv", que es el ID del elemento al que he asignado el event "click".

Pero lo que ocurre es que si lo hago sobre el Span, captura el Id del span, etc...

Hay alguna forma de conseguir lo que intento? (que, haciendo click sobre un elemento "contenedor" , con un ID determinado, capture solo ese ID, independientemente de sobre que elemento se hace el Click?? )

Espero que mi codigo sirva como ejemplo.

Pd: busco soluciones dentro de vanilla JS, que es lo que estoy aprendiendo.

const myListOfElements = [
    {
     id: 1,
     name: "Elemento 1",
     img: "https://placehold.it/300?text=Elemento%201"
    },
    {
     id: 2,
     name: "Elemento 2",
     img: "https://placehold.it/300?text=Elemento%202"
    },
    {
     id: 3,
     name: "Elemento 3",
     img: "https://placehold.it/300?text=Elemento%203"
    }
   ];

const createElements = (elementsArray) => {
     const container = document.querySelector('#container');
     
     elementsArray.forEach(({id, name, img}) => {
        const element = document.createElement('div');
        element.setAttribute('id', 'idDiv')
        
        // creamos el span y lo añadimos al elemento padre
        const elementSpan = document.createElement('span');
        elementSpan.setAttribute('id', 'idSpan')
        elementSpan.innerText = name;
        element.appendChild(elementSpan);
        
        // creamos la imagen y la añadimos al elemento padre
        const elementImg = document.createElement('img');
        elementImg.setAttribute('src', img);
        elementImg.setAttribute('alt', name);
        elementImg.setAttribute('id', 'idImg');
        element.appendChild(elementImg);
        
        // añadimos el eventListenet
        element.addEventListener('click', () => {
          const targetElement = document.querySelector('#oneText');
          targetElement.innerText = event.target.id;
          console.log(event.target.id);
        });
        
        // añadimos el elemento al nodo contenedor
        container.appendChild(element);
     }) 
   }
   
   createElements(myListOfElements);
<!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>
    

<p id="demo"></p> -->

<span id="oneText">ESTE TEXTO DEBE CAMBIAR</span>
<div id="container">
</div>



<script type="text/javascript" src="prueba.js"></script>
</body>
</html>

2
  • .parentElement();
    – Bryro
    el 15 jun. 2019 a las 16:33
  • Disculpa, pero podrias ser mas preciso? Te refieres a incoporarlo al addEvent? element.addEventListener.parentElement()
    – notADevYet
    el 15 jun. 2019 a las 17:26

1 respuesta 1

1

https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

event.target es quien dispara el evento ( recibe el click )

event.currentTarget es quien está escuchando el evento

const myListOfElements = [{
    id: 1,
    name: "Elemento 1",
    img: "https://placehold.it/50?text=Elemento%201"
  },
  {
    id: 2,
    name: "Elemento 2",
    img: "https://placehold.it/50?text=Elemento%202"
  },
  {
    id: 3,
    name: "Elemento 3",
    img: "https://placehold.it/50?text=Elemento%203"
  }
];

const createElements = (elementsArray) => {
  const container = document.querySelector('#container');

  elementsArray.forEach(({
    id,
    name,
    img
  }) => {
    const element = document.createElement('div');
    element.setAttribute('id', 'idDiv' + id)

    // creamos el span y lo añadimos al elemento padre
    const elementSpan = document.createElement('span');
    elementSpan.setAttribute('id', 'idSpan' + id)
    elementSpan.innerText = name;
    element.appendChild(elementSpan);

    // creamos la imagen y la añadimos al elemento padre
    const elementImg = document.createElement('img');
    elementImg.setAttribute('src', img);
    elementImg.setAttribute('alt', name);
    elementImg.setAttribute('id', 'idImg' + id);
    element.appendChild(elementImg);

    // añadimos el eventListenet
    element.addEventListener('click', (event) => {
      const targetElement = document.querySelector('#oneText');
      targetElement.innerText = 'recibe:' + event.target.id +
        ' escucha:' + event.currentTarget.id;
      console.log(
        'R:', event.target.id,
        'E', event.currentTarget.id
      );
    });

    // añadimos el elemento al nodo contenedor
    container.appendChild(element);
  })
}

createElements(myListOfElements);
#container>div {
  display: inline-block;
  margin: 2px;
  padding: 20px;
  border: 1px dashed red
}

#container>div span {
  background: #fe0;
  margin: 2px;
  padding: 2px;
}

#container {
  margin-bottom: 200px;
}
<!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>

  <p id="demo"></p> -->

  <span id="oneText">ESTE TEXTO DEBE CAMBIAR</span>
  <div id="container">
  </div>

</body>

</html>

1
  • 1
    wow...no pense que seria tan sencillo ...(sencillo el usar currentTarget ...no sencillo el entender el concepto :D ) . Pero juraria que cuando estaba revisando el objeto del generado por el event, currentTarget era ="" Muchisimas gracias, voy a darle un buen repaso . Me has ayudado un monton!
    – notADevYet
    el 15 jun. 2019 a las 17:35

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.