0

I'm making a "TV guide" which gets data from an xml file. Here's what I have so far:

$(document).ready(function(){
$.ajax({
    type: "GET",
    url: "programmes.xml",
    dataType: "xml",
    error: function (xhr, status, error) {
        console.log(status, error);
    },
    success: function(xml) {

        var programmeOne = $(xml).find('programme').first();
        $(xml).find('[programme[id="ch1pg1"]').text();
        $('.p1').text(programmeOne.find('title').text());

    }

});

And here's the XML:

<channel id="bbc1" source="Sky" date="20/12/2014">
<programme id="ch1pg1">
  <desc>The latest news, sport, business and weather from the BBC's Breakfast team.</desc>
  <title>Breakfast</title>
  <start>0900</start>
  <end>1100</end>
</programme>
<programme id="ch1pg2">
  <desc>James Martin presents the weekly cooking show. [HD] [S]</desc>
  <title> Kitchen</title>
  <start>1100</start>
  <end>1200</end>
</programme>
<programme id="ch1pg3">
  <desc>descriptions [HD] [S]</desc>
  <title>second  Kitchen</title>
  <start>1200</start>
  <end>1300</end>
</programme>

When I remove

$(xml).find('[programme[id="ch1pg1"]').text();

The code works, but all programme 1's from each channel use the same title from ch1pg1.

How can I make the function only use the "title" element from the parent element "programme" which has an id of "ch1pg1"?

1 Answer 1

1

Firstly when searching by id you can use the # selector to make things both quicker and shorter.

Your second line of code does not work because you are returning a string, and then attempting to use jQuery methods on it, which will not work. Instead return the jQuery object and use that. Try this:

success: function(xml) {
    var $programmeOne = $(xml).find('#ch1pg1');
    $('.p1').text($programmeOne.find('title').text());
}

Example fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.