Reputation: 35
I am trying to call an function into my <p>
which should call the numbers(while loop) 1 to 25. But I'm not sure how to move forward.
How would I append this info into the paragraph tag without using console.log()
or document.write()
but using instead document.createElement
and node.append
to insert my results into HTML?
How would I call this function inside a p tag in a DOM HTML?
function oneThroughTwentyFive() {
let count = 1
while(count <= 25) {
count++
}
}
Upvotes: 1
Views: 2107
Reputation: 2660
This will render a <p>
element with the numbers 1 through 25 within it.
<html>
<body>
</body>
<script>
let p = document.createElement('p');
let script = document.createElement('script');
script.innerHTML = `
let numbers = "";
for (let e = 1; e <= 25; e++) numbers += e + " ";
document.currentScript.parentNode.innerHTML = numbers;
`
p.appendChild(script)
document.body.appendChild(p)
</script>
</html>
Basically what this does is:
<p>
element<script>
element<script>
element<script>
element to the <p>
element<p>
element (which now has the Javascript code within it)
to the bodyAnd this is what the Javascript in the <p>
element does:
<p>
which contains the <script>
<p>
element (including the JS code used to create the numbers) with the numbers.The Javascript code used to create the numbers is gone, so the final element will look like this:
<p>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25</p>
Upvotes: 1
Reputation: 22432
that ?
const pTag = document.querySelector('p#pTag')
for (let i=1;i<=25;++i) pTag.textContent += i+' '
// -------------------------------------------
// the method name say's all
let otherP = document.createElement('p')
// just a trick as many in JS
otherP.textContent = Array.from(Array(10),(_,i)=>i+25).join(' ')
// append otherP in the right place on the DOM
document.body.appendChild( otherP )
<p id="pTag"></p>
Upvotes: 0