-1
function getNotRec(articleLink) {
  var req = new XMLHttpRequest();
  req.open("GET", articleLink, true);
  req.onreadystatechange = function(aEvt) {
    if (req.readyState === 4) {
      if (req.status === 200) {
        //console.log(req.responseText);
        findNotRecTag(req.responseText);
      }
      else {
        console.log("Error loading page\n");
      }
    }
  };
  req.send(null);
}

function findNotRecTag(htmlText) {
  var notRec = htmlText.getElementsByClassName("t_black");    //here
  for (var i = 0; i < notRec.length; i++) {
    console.log("notrec" + notRec[i].innerText);
  }
}

I wish to get some 'class' on another website using JavaScript. So I am using XMLHttpRequest and successfully received.

but when i attempt to extract some class from received, I'm getting errors on the console:

"Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined",    
"Uncaught TypeError: Cannot read property 'querySelector' of undefined"

I think Chrome know what am I doing but she is.. not like that, I guess

Main Question: There is any method using getElementsByClassName on the string or like something?

I've tried querySelector also but it doesn't work (see error messages above).

connexo
  • 53,704
  • 14
  • 91
  • 128
hiru
  • 33
  • 4

1 Answers1

0

req.responseText is obviously undefined according to the error message you're getting. To answer you core question, here's how you select elements from a string:

// here's your string
const htmlText = `<div><p class="p">fsdf</p><p class="p">wfdfds<p></div>`

// create an element
const fakeEl = document.createElement('div')
// and put the htmlText as innerHTML on that element
fakeEl.innerHTML = htmlText;

// now you can use all kinds of selector methods on that element
console.log(fakeEl.getElementsByClassName('p'));
console.log(fakeEl.querySelectorAll('.p'));
connexo
  • 53,704
  • 14
  • 91
  • 128