0

I'm currently just trying to test and find out how to pull information from cnn.com and get the some of the titles of the articles with the class name, "cd__headline-text." However, when I use the $.ajax function to get the titles of the articles on cnn with that class name I get an error that says response.getElementsByClassName is not a function.

Below is the code that prompts this error to happen:

$(document).ready(function(){
    $("button").click(function(){
    console.log("hi test");
    $.ajax({
        url: "https://www.cnn.com",
        cache: false,
        success: function(response){
            filter = response.getElementsByClassName("cd__headline-text");
            console.log(filter);
        }
    });

    });
});

My current console.log(response); output is in this link:

https://pastebin.com/SsBSPdBL

Rajat Khare
  • 522
  • 8
  • 26

2 Answers2

0

However, when I use the $.ajax function to get the titles of the articles on cnn with that class name I get an error that says response.getElementsByClassName is not a function.

Because response is not a Node or DOM element.

You need to parse the XML and find the element by attribute

xmlDoc = $.parseXML( response ),
$xml = $( xmlDoc ),

and now get the required value from it

$title = $xml.find( "[class='cd__headline-text']" );

or

$title = $xml.find( ".cd__headline-text" );

Or if the value is already an HTML, then simply

 $( response ).find( ".cd__headline-text" )
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Try this, or check URL

 $(document).ready(function(){
    $("button").click(function(){
    console.log("hi test");
    $.ajax({
       url: "https://www.cnn.com",
       cache: false,
       success: function(response){
           $(response).find('.cd__headline-text').each(function(){
              console.log($(this).html());
           });
      }
    });
    });
});

Hope this will help you.

Sunil Dora
  • 1,407
  • 1
  • 13
  • 26
  • Hi, I tried your suggestion, but nothing gets printed in the console. Do you know why? – Rajat Khare Nov 10 '17 at 06:32
  • No 'Access-Control-Allow-Origin' header is present on the requested resource. I am facing an error on the console while trying your content. check in my [fiddle](https://fiddle.jshell.net/sunildora_94/8qy8bL01/3/) – Sunil Dora Nov 10 '17 at 07:13
  • Now check I tried my URL, and it's working perfectly. I have given 'Access-Control-Allow-Origin' permission in my link. – Sunil Dora Nov 10 '17 at 07:20
  • so how do I get the titles from cnn.com then? – Rajat Khare Nov 10 '17 at 07:22
  • check this once- [URL](https://stackoverflow.com/questions/42326777/retrieving-rss-xml-news-data-using-jquery-ajax-in-django) – Sunil Dora Nov 10 '17 at 07:27