How to get the children of the $(this) selector?

前端 未结 18 2488
日久生厌
日久生厌 2020-11-22 05:10

I have a layout similar to this:

and would like to use a jQuery selector to selec

18条回答
  •  我寻月下人不归
    2020-11-22 05:32

    You can find all img element of parent div like below

    $(this).find('img') or $(this).children('img')
    

    If you want specific img element you can write like this

    $(this).children('img:nth(n)')  
    // where n is the child place in parent list start from 0 onwards
    

    Your div contain only one img element. So for this below is right

     $(this).find("img").attr("alt")
                      OR
      $(this).children("img").attr("alt")
    

    But if your div contain more img element like below

    3 4

    then you can't use upper code to find alt value of second img element. So you can try this:

     $(this).find("img:last-child").attr("alt")
                       OR
     $(this).children("img:last-child").attr("alt")
    

    This example shows a general idea that how you can find actual object within parent object. You can use classes to differentiate your child object. That is easy and fun. i.e.

    3 4

    You can do this as below :

     $(this).find(".first").attr("alt")
    

    and more specific as:

     $(this).find("img.first").attr("alt")
    

    You can use find or children as above code. For more visit Children http://api.jquery.com/children/ and Find http://api.jquery.com/find/. See example http://jsfiddle.net/lalitjs/Nx8a6/

提交回复
热议问题