Sandeep Singh
Sandeep Singh

Reputation: 897

How to select $this of a parent function?

I have few divs with the class weather-widget and a parameter xml-url. Using Jquery I am looping through all divs with the weather-widget class. Then in the call back function i am making ajax request to pull in xml data. Then in the success function I am looping through content. My question is how can I select the weather-widget and appent its HTML. I have

HTML

<div class="weather-widget" xml-url='www.firstURL.com/output.xml'>
    <div class="panel panel-default">
        <div class="panel-heading">Vancouver</div>
        <ul class="list-group">
            <!-- append using jquery -->
        </ul>
    </div>
</div>
<div class="weather-widget" xml-url='www.secondURL.com/output.xml'>
    <div class="panel panel-default">
        <div class="panel-heading">Abbotsford</div>
        <ul class="list-group">
            <!-- append using jquery -->
        </ul>
    </div>
</div>

Javascript

$(".weather-widget").each(function(){


    $.ajax({
        url: $(this).attr('xml-url'),
        type: "GET",
        dataType: "xml",
        success: function(xml){
            $(xml).find("entry").each(function () {

               $(What Should I PUT HERE).find(ul).append('<li class=\"list-group-item\">'+$(this).find("title").text()+'</li>');

            });
        }
    }); 


});

Upvotes: 1

Views: 70

Answers (3)

adeneo
adeneo

Reputation: 318182

You already have the element, it's the second argument in the each() loop

$(".weather-widget").each(function(index, elem) {
    $.ajax({
        url: $(this).attr('xml-url'),
        type: "GET",
        dataType: "xml",
        success: function(xml) {
            $(xml).find("entry").each(function() {
                    $(elem).find('ul').append('<li class=\"list-group-item\">' + $(this).find("title").text() + '</li>');
            });
        }
    });
});

Upvotes: 3

GregL
GregL

Reputation: 38103

Just store away the element inside the function, which is accessible inside your success callback.

$(".weather-widget").each(function(){
    var $thisWidget = $(this);

    $.ajax({
        url: $(this).attr('xml-url'),
        type: "GET",
        dataType: "xml",
        success: function(xml){
            $(xml).find("entry").each(function () {

               $thisWidget.find(ul).append('<li class=\"list-group-item\">'+$(this).find("title").text()+'</li>');

            });
        }
    }); 


});

Upvotes: 0

user2575725
user2575725

Reputation:

Well one option is using closures:

$(".weather-widget").each(function(){
   (function(el){
       // ..
       $(xml).find("entry").each(function () {
           $(el).find(ul).append('<li class=\"list-group-item\">'+$(this).find("title").text()+'</li>');
         // ^^^^
       });
       // ..
   })(this);
});

Upvotes: 0

Related Questions