Reputation: 3785
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!
Upvotes: 1
Views: 401
Reputation: 92
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>
Upvotes: 1
Reputation: 13070
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>
Upvotes: 2