Onur Kucukkece
Onur Kucukkece

Reputation: 1748

get subchild value for a specific child in xml via jquery

I'am a newbie in jquery and I want to parse subchilds in a xml file for a specific child attribute, for example, I have this cities and districts list

<city name="ANKARA"> 
  <distr>BEYPAZARI</distr>
  <distr>GÜDÜL</distr>
  <distr>KAZAN</distr>
  <distr>ÇANKAYA</distr>
</city>
<city name="İSTANBUL">
 <distr>EMİNÖNÜ</distr>
 <distr>ÇATALCA</distr>
 <distr>BEYOĞLU</distr>
 <distr>BEYKOZ</distr>
 <distr>BEŞİKTAŞ</distr>
</city>

I use this code to get city list

 $(xml).find('city').each(function(){
     var city = $(this).attr("name");
     $("<option>").text(city).appendTo("#cityList");
 }); 

but I don't how to get the district list of for example Ankara, someone could help me please thanks in advance

Upvotes: 2

Views: 2285

Answers (3)

Onur Kucukkece
Onur Kucukkece

Reputation: 1748

both answers above helped me to get exactly what I want,

$(xml).find('city[name="ANKARA"]').find('distr').each(function(){
    var distr = $(this).text();
    $("<option>").text(distr).appendTo("#district_list");
});

thanks a lot

Upvotes: 0

Chandu
Chandu

Reputation: 82893

Try this to iterate through all the city and the child districts

$(xml).find('city').each(function(){
     var city = $(this).attr("name");
     $('distr', this).each(function(){
       //Add your code here to deal with Districts
    }
   });
   $("<option>").text(city).appendTo("#cityList");
 }); 

Upvotes: 0

artlung
artlung

Reputation: 34013

 $(xml).find('city[name="ANKARA"]').each(function(){
     var city = $(this).attr("name");
     $("<option>").text(city).appendTo("#cityList");
 }); 

That's the "attribute equals" selector you want.

Upvotes: 1

Related Questions