-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).

7
  • req.responseText is obviously undefined.
    – connexo
    Aug 11, 2018 at 7:16
  • If check the console, it's not. it has values
    – hiru
    Aug 11, 2018 at 7:17
  • Use DOMParser. You can’t use DOM methods on strings. Aug 11, 2018 at 7:19
  • I checked passed element on findNotRecTag, it is undefined what you told. thanks
    – hiru
    Aug 11, 2018 at 7:22
  • There are any method to convert string to DOM object? I am newbie on javascript
    – hiru
    Aug 11, 2018 at 7:23

1 Answer 1

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'));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.