William Elliot
William Elliot

Reputation: 35

Adding a function into a DOM element

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

Answers (2)

marsnebulasoup
marsnebulasoup

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:

  1. Create a <p> element
  2. Create a <script> element
  3. Add the Javascript code to display the numbers into the <script> element
  4. Append the <script> element to the <p> element
  5. Append the <p> element (which now has the Javascript code within it) to the body

And this is what the Javascript in the <p> element does:

  1. Loop through all numbers from 1 to 25
  2. Add each number plus a space (so the numbers won't be jammed up against each other) to the numbers variable
  3. Find the parent element of the current script (in this case the <p> which contains the <script>
  4. Overwrite the entire content of the <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

Mister Jojo
Mister Jojo

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

Related Questions