1

I have a list and I want to get image and text value using JavaScript how can i do that? right now i'm getting only selected li id.

My Code:-

function reply_click()
{
    console.log(event.target.id);
}
ul.coinList{ margin:0px; padding:0px;}
ul.coinList li{ list-style:none; border:1px solid #ccc; padding:10px; display:flex; margin-bottom:20px; display:block;}
<ul class="coinList">

<li id="1" onClick="reply_click();">
<img src="https://via.placeholder.com/140x100" />
<span class="coinText">one</span>
</li>

<li id="2" onClick="reply_click();">
<img src="https://via.placeholder.com/140x100" />
<span class="coinText">two</span>
</li>

</ul>

Thanks for your efforts!

1
  • 1
    Don't use inline event handlers or running numbers as ids: jsfiddle.net/vt37hz8y Commented Jun 2, 2022 at 7:18

2 Answers 2

2

First of all the event listener can just be on the <ul>. And then you can find the <li> by using Element.closest() from the element that was clicked (e.target). From there you can find the two child elements with Document.querySelector().

function reply_click(e) {
  let li_elm = e.target.closest('li');
  let img_elm = li_elm.querySelector('img');
  let span_elm = li_elm.querySelector('span');
  console.log('id:', li_elm.id, 'img:', img_elm.src, 'text:', span_elm.textContent);
}

document.querySelector('ul.coinList').addEventListener('click', reply_click);
ul.coinList {
  margin: 0px;
  padding: 0px;
}

ul.coinList li {
  list-style: none;
  border: 1px solid #ccc;
  padding: 10px;
  display: flex;
  margin-bottom: 20px;
  display: block;
}
<ul class="coinList">
  <li id="1">
    <img src="https://via.placeholder.com/140x100" />
    <span class="coinText">one</span>
  </li>
  <li id="2">
    <img src="https://via.placeholder.com/140x100" />
    <span class="coinText">two</span>
  </li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

1

function reply_click()
{
    if(event.currentTarget.tagName==="LI") {
      alert(event.currentTarget.id);
      alert(event.currentTarget.querySelector('img').src);
    }
}
ul.coinList{ margin:0px; padding:0px;}
ul.coinList li{ list-style:none; border:1px solid #ccc; padding:10px; display:flex; margin-bottom:20px; display:block;}
<ul class="coinList">

<li id="1" onClick="reply_click();">
<img src="https://via.placeholder.com/140x100" />
<span class="coinText">one</span>
</li>

<li id="2" onClick="reply_click();">
<img src="https://via.placeholder.com/140x100" />
<span class="coinText">two</span>
</li>

</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.