garrethwills garrethwills - 1 month ago 15x
HTML Question

textContent not updating HTML

Using Javascript I have created a script to generate random text in a paragraph. It works. When I print to the console I see a paragraph of text.

console.log(randParagraph(sentLength(5,8), '', ipsumText, sentLength(5,12)));

Now I want to update some text in an html file with that paragraph on click of a button. The below is how I thought it should be done.

const randParagraph = (len, end, words, wordLen) =>
[...Array(len)].map(() => addCommaAfter(fullSentWithEnd,sentLength(3,8)))
.join(' ') + (end || '');

function myFunction() {
var x = (randParagraph(sentLength(5,8), '', ipsumText,sentLength(5,12)));
var y = document.getElementById("ipsum-text").textContent = "x";

My assumption is if console.log works, I should store that result in a variable which is what I'm trying to do with var x.

Then in var y I can use getElementById to change the html text.

<button onclick="myFunction()">change text</button>

<p class="bodyCopy" id="ipsum-text">gimme some ipsum</p>

Is this the correct way to go about it? It's not working.
I know one would use jquery to do this, but I haven't learned it yet. I'm still learning javascript.


Try it like this:

function myFunction() { 
    var x = (randParagraph(sentLength(5,8), '', ipsumText,sentLength(5,12)));
    document.getElementById("ipsum-text").innerHTML = x;

Note that you don't want to use quotes around x