Jquery statement that returns the last Child of different elements

Asked

Viewed 147 times

1

Hi, I’m doing some exercises for a programming course I took. I came across this task and do not know how to solve it, someone has some hint?

Make a jQuery statement that selects all elements that are the last children in img HTML or that are the last children in H3 HTML

1 answer

2

To select more than one element in jquery, just pass other filters on the selector using the comma, for example to select the last image and the last H3 on the page I can call as follows:

var lastBandImageAndName = $('img:last, h3:last');

If I want to take all the last elements inside a div, using the same example above:

var lastBandImageAndName = $('div img:last, div h3:last');


Javascript

$(document).ready(function()
{
    var lastBandImageAndName = $('img:last, h3:last');

    lastBandImageAndName.each(function()
    {
       var tag = $(this).prop('tagName');
       if(tag === 'IMG')
       {
          $('#result').append('Última imagem URL = '+ $(this).prop('src'));
       }
       else if(tag === 'H3')
       { 
          $('#result').append('Último H3 texto = ' +  $(this).text());  
       }    
    });  
});

I created a Fiddle with the code above, if you want to take a look >> https://jsfiddle.net/h01gL4a1/

Browser other questions tagged

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