How to get the first child id inside the div using JQuery

前端 未结 7 1858
心在旅途
心在旅途 2020-12-18 21:47

How to get the first child id inside the div using JQuery.

Sample code:


                      
相关标签:
7条回答
  • 2020-12-18 22:14

    To make things super clear, this is what to do in order to find any element within a certain element you already can access, in this case that is the element with id='e1':

    <style>
      .c1{ border:2px solid red; padding: 12px; background: lightyellow }
      .c2{ border:2px solid green; padding: 12px; background: lightyellow }
      .c3{ border:2px solid blue; padding: 12px; background: lightyellow }
    </style>
    
    <div class='c1' id='e1'>
      <div class='c2' id='e2'>
        <div class='c3' id='e3'>text</div>
      </div>
    </div>
    

    The following line get's you div e2:

    var child2 = $('#e1').find(".c2");
    

    The following lines both get you div e3:

    var child3   = $('#e1').find(".c3");
    var child3_1 = $('#e1').find(".c2 :first");
    

    To change something about these, you have to use the objects like this:

    $(child2).css('background-color','white');
    $(child3).css('border','4px dotted pink');
    $(child3_1).css('color','#ef2323');
    

    I hope this is clear and helpful.

    0 讨论(0)
  • 2020-12-18 22:16

    Use this to get first element of id1 element:

        $("#id1").children(":first");
    
    0 讨论(0)
  • 2020-12-18 22:23
    $('#id1:first-child').attr('id')
    
    0 讨论(0)
  • 2020-12-18 22:29

    If you want immediate first child you need

    $(element).first();
    

    If you want particular first element in the dom from your element then use below

    var spanElement = $(elementId).find(".redClass :first");
    $(spanElement).addClass("yourClassHere");
    

    try out : http://jsfiddle.net/vgGbc/2/

    0 讨论(0)
  • 2020-12-18 22:32

    Below Answer Will Select First 'a' Element under element With ID - 'id1" ( As per Asked in Question )

    $('#id1 a:first-child').attr('id')
    

    Below Code will only Select First Div with ID - 'id1' So it will select that div not child element of div ( But its not as per asked by question in answer )

    $('#id1:first-child').attr('id')
    
    0 讨论(0)
  • 2020-12-18 22:34

    $("#form .form-group").first();

    May be helpful for someone.

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