简体   繁体   中英

How to get first-child of element using $(this) in jquery?

<div id="idname">
<div class="badge">
  <div class="icon abc_badge"></div>
  <div class="badges_info">
   <h4>some text</h4>
  </div>
 </div>
<div class="badge">
  <div class="icon xyz_badge"></div>
  <div class="badges_info">
   <h4>some more text</h4>
  </div>
 </div>
</div>

<script>
    $(document).ready(function() {
        $(".badge").click(function () {
            var a = $(this+':first-child');
            var iconDiv = a.html();
            alert(iconDiv);
        });
    });
</script>

In above jquery code I want <div class="icon abc_badge"></div> of each div having class badge . In short I want first child of each div this reference to $(this) .

Thanks.

You can apply .find() here, so use:

var a = $(this).find(':first-child');

instead of:

var a = $(this+':first-child');

Fiddle Demo

You can use children() in combo with first() .

$(this).children().first()

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

From https://api.jquery.com/children/

You can use like this:

$(document).ready(function()
{
    $(".badge").click(function () {
        var a = $(this).find(':first-child');
        var iconDiv = a.text();
        alert(iconDiv);
    });
});

Use children nth child like below :

<script>
    $(document).ready(function(){
        $(".badge").click(function () {
            var a = $(this).children(':nth-child(0)');
            var iconDiv = a.html();
            alert(iconDiv);
        });
    });
</sctipt>

OR call first() on children()

<script>
        $(document).ready(function(){
            $(".badge").click(function () {
                var a = $(this).children().first();
                var iconDiv = a.html();
                alert(iconDiv);
            });
        });
    </sctipt>

It seems you need the outerHTML:

Demo: http://jsfiddle.net/w3Js2/1/

$(".badge").click(function () {
    var $a = $(this).find(':first-child');
    var h = $a[0].outerHTML;
    alert(h);
});

Having a look at jQuery.find() code here it seems that .find() is then translated in jQuery Selector Context ..

This Code works

var a = $(':first-child',this);

Demo Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM