PhilChill PhilChill - 4 years ago 88
Javascript Question

How to grab Image url and title from elements above in same article

Hi Guys i got a question.
How can I get onclick the image url and title from divs in my webpage?

This is the structure of the article:

<article class="white-panel">
<img src="image url to grab" alt="">
<h4><a href="#">Title to grab</a></h4>
<p><a href="#"><span class="fa fa-whatsapp"></span> Onclick grab image and title with Jquery</a></p>
<p><a href="#"><span class="fa fa-facebook"></span> Auf Facebook teilen</a></p>

I need this for several article elements on page but they all got the same sructure.

Answer Source

If the structure of all these articles is the same, the following should work:

$('article p:first-of-type a').click(function() {
    // Get the parent article of the clicked link
    var parentArticle = $(this).parents('article');
    // Find the img src and h4 (title) text
    console.log($(parentArticle).find('h4 a').text());

The console.log() is just to see the values, you could store these in variables for further use.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download