0

I'm trying to add an id variable (in this case, demo) to the end of the link but I can't make it work, how can I do it?

var request = new XMLHttpRequest()

request.open('GET', 'https://discordapp.com/api/users/412315079598407691', true)
request.setRequestHeader("Authorization", "Bot bot-token")
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myObj = JSON.parse(this.responseText);
      document.getElementById("demo").innerHTML = myObj.avatar;
    }
  };
request.send()

function myFunction() {
    var x = document.createElement("IMG");
    x.setAttribute("src", `https://cdn.discordapp.com/avatars/412315079598407691/`+ demo);
    x.setAttribute("width", "350");
    document.body.appendChild(x);
  }
tmarshguy
  • 69
  • 1
  • 1
  • 3
  • 2
    What **exactly** is not working with the given code? You haven't defined `demo` anywhere in that snippet – Nico Haase Feb 02 '21 at 21:50
  • 2
    Since you're using a template literal, you can use `${demo}` inside the literal instead of concatenation. – Barmar Feb 02 '21 at 21:51
  • i've added the code snippet calling the demo there – tmarshguy Feb 02 '21 at 21:52
  • You added a code snippet but again, no where in the above do you actually define demo. Are you saying that demo = innerHtml of the element demo? Those are two different things. – basic Feb 02 '21 at 21:58
  • (*There was an overlap with basic's comment above*) There seems to be a DOM object with the ID `demo` (at least your JS code relies on this), but nothing like `var demo = foo` is happening anywhere. – Pida Feb 02 '21 at 21:59
  • 1
    @Pida [Do DOM tree elements with ids become global variables?](https://stackoverflow.com/q/3434278) - an element with `id="demo"` actually creates a `window.demo` property. So, it exists as a global variable. – VLAZ Feb 02 '21 at 22:02
  • @VLAZ Wow, I've never heard of this! However, I don't think it's a good idea to rely on this. Even a dash in the id attribute breaks this functionality. @tmarshguy You didn't mention what exactly is not working yet. "foo" + demo might give you something like `foo[object HTMLDivElement]`, is this what's happening? – Pida Feb 02 '21 at 22:13

1 Answers1

-1

Instead of ``https://cdn.discordapp.com/avatars/412315079598407691/+ demo

try doing https://cdn.discordapp.com/avatars/412315079598407691/${demo} Please make sure that demo.toString() returns what you want. As things can get weird when you stringify an object.

destroyer22719
  • 356
  • 2
  • 6