2

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.

garrethwills
  • 41
  • 1
  • 7
  • 2
    instead of textContent, use: innerHTML – Patrick Aleman Sep 05 '16 at 11:15
  • I actually had that at first, but after reading some articles understood it to be incorrect. Not sure if that is the case, but it still doesn't print the paragraph. It just prints "x". – garrethwills Sep 05 '16 at 11:17
  • 2
    It should, because you told it so. `"x"` is equivalent to `the letter x literally`. If you want to show the content of the variable, just write `x` – devnull69 Sep 05 '16 at 11:18
  • Does this answer your question? [nodeValue vs innerHTML and textContent. How to choose?](https://stackoverflow.com/questions/21311299/nodevalue-vs-innerhtml-and-textcontent-how-to-choose) – Liam Feb 01 '21 at 10:47

2 Answers2

1

This code works (example purpose) :

<div id="textContent">There's some text here!</div>

<script>
    function updateContent() {
        document.getElementById("textContent").textContent = "Newer text!";
    }

    updateContent();
</script>

When you're calling your x variable, you don't need use " character. This code sould work :

function myFunction() {
    var x = randParagraph(sentLength(5,8), '', ipsumText, sentLength(5,12));
    document.getElementById("ipsum-text").textContent = x;
}
cmizzi
  • 188
  • 1
  • 14
-1

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

Michael
  • 1,247
  • 1
  • 8
  • 18