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>
CodePudding user response:
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")