0

I have the following script inside html, but the output inside html is without style.

How can I best style the script output so as it fits within the existing html structure?

I thought this may be achieved by getting the output by id, but have not figured that out.

<script>
    var myArray = [
        "<ul><p>Alef</p><p>1</p>",
        "<ul><p>Bet</p><p>2</p>"
    ];

    var randomItem = myArray[Math.floor(Math.random()*myArray.length)];

    document.body.innerHTML += randomItem;
</script>
3
  • 1
    The HTML in your array is invalid. A <p> cannot be a child of a <ul>. Only a <li> can Commented Jun 7, 2022 at 16:54
  • 1
    Instead of setting innerHTML on the body, try creating a new element that you can then add styles to. developer.mozilla.org/en-US/docs/Web/API/Document/createElement Commented Jun 7, 2022 at 16:56
  • @scott How would this look in practice? Commented Jun 7, 2022 at 17:02

1 Answer 1

1

Instead of setting innerHTML on the body, try creating a new element that you can then add styles to, and then adding that element to the body.

const randomItemElement = document.createElement("div");
randomItemElement.innerHTML = randomItem;
randomItemElement.style.color = "blue";

document.body.appendChild(randomItemElement);

You can also create a CSS class and set that on your element instead of setting individual properties, e.g. randomItemElement.classList.add("myClass")

Sign up to request clarification or add additional context in comments.

2 Comments

How would I specify 'max-width'? The dash seems to make problems.
.style.maxWidth = "100px"; works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.