Home > Software engineering >  Make a variable by giving the value of an html DOM
Make a variable by giving the value of an html DOM

Time:10-21

I wanna make a variable like this:

const number = document.getElementById('number');

which can be changed as this:

number = Math.floor(1   Math.random() * 20);

and I saw that I can select body by doing this:

const body = document.body;
body.onload = AnyFunction;

but I'm also trying to select that id but I don't how to. Big thanks in advance :)

CodePudding user response:

not really sure what you want to achive.

The first code: const number = document.getElementById('number'); Is getting an HTML Element from the DOM like a DIV or a Paragraph with the ID of Number. Like this:

<div id="number">...</div> This is not a javascript variable like const test = 12134; it is a HTML Object. You can save content to the element by setting the innerText property like:

   const paragraph = document.getElementById("number");
   const number = 12345;
   paragraph.innerText = number;

Then you have inserted the numer 12345 into an existing HTML Element with the ID number.

Hope this helps a littel bit. Sorry if I missed something, is my first question ;-)

  • Related