Printing JS variable as HTML

How can I use JavaScript code to define a HTML code.
I mean that i want the i in the program below to be shown as the heading 1 (h1):

for(i=0;i<10;i++)
{ if(i===3){ continue; }
document.write(i);
if(i===4){ break;
}
}
Thank you, guys.

Try

document.write("<h1>"+i+"</h1>");

Ok, @ivan’s answer is not wrong, I think to get a better understanding of the relationship between html and javascript a more thorough approach would be this

const h1 = document.createElement('h1')  // create an <h1> element object
h1.innerText = i                         // set the content of the element to i
document.body.appendChild(h1)            // add element to the document body

// or

document.querySelector('#someElement').appendChild(h1)

This will allow you to put it anywhere in the document

any time you say document.querySelector or document.getElementById or $('#someElement') you are creating an element object(jquery approach is a wrapped element), just like with document.createElement, so any element in the document can be represented by a javascript object

1 Like