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

前端 未结 18 2187
日久生厌
日久生厌 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:39

    You can use Child Selecor to reference the child elements available within the parent.

    $(' > img', this).attr("src");
    

    And the below is if you don't have reference to $(this) and you want to reference img available within a div from other function.

     $('#divid > img').attr("src");
    
    0 讨论(0)
  • 2020-11-22 05:39

    Also this should work:

    $("#id img")
    
    0 讨论(0)
  • 2020-11-22 05:39

    If your img is exactly first element inside div then try

    $(this.firstChild);
    

    $( "#box" ).click( function() {
      let img = $(this.firstChild);
      console.log({img});
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="box"><img src="https://picsum.photos/seed/picsum/300/150"></div>

    0 讨论(0)
  • 2020-11-22 05:41

    You could use

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
     $(this).find('img');
    </script>
    
    0 讨论(0)
  • 2020-11-22 05:43

    The direct children is

    $('> .child-class', this)
    
    0 讨论(0)
  • 2020-11-22 05:43

    Here's a functional code, you can run it (it's a simple demonstration).

    When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.

    $(document).ready(function() {
      // When you click the DIV, you take it with "this"
      $('#my_div').click(function() {
        console.info('Initializing the tests..');
        console.log('Method #1: '+$(this).children('img'));
        console.log('Method #2: '+$(this).find('img'));
        // Here, i'm selecting the first ocorrence of <IMG>
        console.log('Method #3: '+$(this).find('img:eq(0)'));
      });
    });
    .the_div{
      background-color: yellow;
      width: 100%;
      height: 200px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="my_div" class="the_div">
      <img src="...">
    </div>

    Hope it helps!

    0 讨论(0)
提交回复
热议问题