1

if im enter the webpage 127.0.0.1/?id=1 and type in the browser console

var str = document.getElementsByClassName("xyz");
document.write(str.length);

i'm receiving the number i needed.

but if i use the same code with fetch in the console. i always get the number 0. how do i fix it?

fetch("http://127.0.0.1/?id=1", {
      "credentials": "include",
     "headers": {
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
           "Accept-Language": "en-US,en;q=0.5",
           "Upgrade-Insecure-Requests": "1",
           "Cache-Control": "max-age=0"
      },
      "method": "GET",
      "mode": "cors",
 })

.then(response => response.text())
    .then(str => {

var str = document.getElementsByClassName("xyz");
document.write(str.length);
      
})

I want to get same number as I recevied in the first try. how to make getElementsByClassName and fetch work together?

  • how is the fetch at all related to elements with class `xyz`? – Jaromanda X Jan 26 '20 at 02:28
  • try to avoid using `document.write` unless you're fully aware of the consequences ... for debugging, use `console.log` instead - that won't mess with your DOM – Jaromanda X Jan 26 '20 at 02:29
  • 1
    You have: .then(response => response.text()) .then(str => { var str = document.getElementsByClassName("xyz"); document.write(str.length); So you are passing `str` in, but then declaring a new variable called `str` which overrules it. The document it refers to is still your current document (where this script is written). The `=>` operator does not _send_ data, as your code suggests. It is a shorthand for declaring a function. – tmdesigned Jan 26 '20 at 02:33
  • @tmdesigned - that's some good detective work - I never would've guessed the question was about parsing HTML received from fetch!!! – Jaromanda X Jan 26 '20 at 02:45
  • First div
    Second div.
    third div
    fourth div
    fivth div

    return 5. but with fetch i get 0

    – johns abraham Jan 26 '20 at 02:46
  • i tried var abc = str.getElementsByClassName("xyz"); document.write(abc.length); but it didnt worked – johns abraham Jan 26 '20 at 02:50
  • @johnsabraham get rid of that intermediary function. Right after the fetch's closing ), in the first "then", console.log your response. Then try parsing it. Then try getting the length. Build up from one working piece to another. – tmdesigned Jan 26 '20 at 03:02
  • i recevied TypeError: str.getElementsByClassName is not a function – johns abraham Jan 26 '20 at 03:02

0 Answers0