What are the best ways to creatively design HTML content generated using JavaScript?

I am currently using Squarespace 7.1 to create a website that features a randomly generated quote in the footer section. The quote is generated from a JavaScript array when the page loads, reloads, or changes. Despite the code functioning as intended (tested on CodePen, JSFiddle, and my Squarespace site), I am struggling to style the output.

I have attempted to style the output using CSS and directly within the HTML container, but it only applies the default styles for that particular section of the page, which do not match the color, alignment, and size I desire for the quote.

Here is the basic HTML code:

<div class="Quote"></div>

Below is the JavaScript code:

function ShowQuote()
  {
    var Quote = [
"Where words fail, music speaks. — Hans Christian Andersen",
"Music is the language of the spirit. It opens the secret of life bringing peace, abolishing strife. — Kahlil Gibran",
// Remaining quotes omitted for brevity
    ];
    var Pick = Math.floor(Math.random() * (Quote.length));
    document.write(Quote[Pick]);
  }
  
  document.addEventListener("load", ShowQuote());

For reference, here are the CSS and HTML styling codes I have tried without success:

CSS:

.Quote {
  display: flex;
  font-family: "Poppins", sans-serif;
  font-weight: 300;
  font-style: Normal;
  font-size: 1em;
  line-height: 1.8em;
  text-align: center;
  color: #1B1B21;
}

HTML (this attempt converted the entire div container into a p element):

<p class="Quote" style="text-align:center;color:blue"></p>

I am seeking guidance on how to properly style the output from the array.

Answer №1

It's important to note that when you utilize document.write(Quote[Pick]);, the content is written in the root document instead of your designated div, resulting in your CSS styles not being applied to the generated HTML.

To ensure your CSS styles are properly applied, consider selecting the div using document.querySelector and then inserting the HTML content using innerHTML.

function ShowQuote(){
    var Quote = [
        "<i>Where words fail, music speaks.</i> — Hans Christian Andersen",
        "<i>Music is the language of the spirit. It opens the secret of life bringing peace, abolishing strife.</i> — Kahlil Gibran",
        "<i>Music, once admitted to the soul, becomes a sort of spirit, and never dies.</i> ― Edward Bulwer Lytton",
        "<i>Music produces a kind of pleasure which human nature cannot do without.</i> ― Confucius"
    ];
    var Pick = Math.floor(Math.random() * (Quote.length));

    document.querySelector('.Quote').innerHTML = Quote[Pick]

};
document.addEventListener("load", ShowQuote());
.Quote {
  display: flex;
  font-family: "Poppins", sans-serif;
  font-weight: 300;
  font-style: Normal;
  font-size: 1em;
  line-height: 1.8em;
  text-align: center;
  color: #1B1B21;
}
<div class="Quote"></div>

Answer №2

document.write is best suited for generating an entire document from scratch. If used on an existing document, it may place the content outside the intended area.

<html>
<!-- your page -->
</html>
....content written using document.write...

It's recommended to have a designated tag in your template for the quote. This tag should be identifiable, whether by class name or unique id.

You can then target that element and update its content with the new quote.

// if the element has an id (footer-quote)
document.querySelector("#footer-quote").innerHTML = "my new quote"

// if the element has a class name (quote)
document.querySelector(".quote").innerHTML = "my new quote"

If there's no suitable element in your template, you can add one dynamically.

let quote = document.createElement("p")
quote.setAttribute("class", "quote")
quote.innerHTML = "my new quote"
document.body.appendChild(quote)

When using the second option, ensure to find the right placement within your template to seamlessly integrate the quote.

Answer №3

document.write can generate new content based on your HTML, disregarding all existing tags, elements, and styles. Instead, consider using either innerText or innerHTML.

If you want to retain the styling from your CSS class while using document.write, you can include an element within it.

For example:

document.write("<div class='Quote'>" + Quote[Pick] + "</div>")

Check out the demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

Retrieving data from an array obtained from the Google Sheets API using PHP

I am currently utilizing PHP to interact with Google Sheets through the Google Sheets API. Upon executing the following command: $my_variable=$service->spreadsheets_values->get($spreadsheetId,$range); The API responds with an object(Google_Service_ ...

My array is not updating after using JSON.stringify

When I click on a fruit like "lime," it moves into my "Green Array." However, after using JSON.stringify on my Green Array, the updated value doesn't show up. Even though I add a new value to my green array causing an increase in count, when I stringi ...

I.E Compatibility Problem with Button CSS Styling

I've created a button with some styling that looks great on Firefox and Chrome, but unfortunately doesn't work quite right on Internet Explorer (all versions). Check out the JsFiddle DEMO : http://jsfiddle.net/Mhded/1/ Below is the code I' ...

What's preventing me from aligning this div in the center?

I'm trying to set up a layout with two centered columns for Tumblr posts on the left side, while keeping a sidebar on the right. Can someone help me achieve this? #wrapper /*applying styles for two columns*/ { display: inline-bloc ...

Find the position of the largest number in an array

Is there a way to retrieve the index of the highest value in an array similar to the one shown below? In the given array, the expected output would be '11'. Array ( [11] => 14 [10] => 9 [12] => 7 [13] => 7 [14] =& ...

A situation where the event onclick fails to occur within NextJS

index.js: function Home () { return <div> <html> <head> <title>Site</title> </head> <body> <div class= 'v5_3' onclick = "func_click()"></div> </b ...

Step-by-step guide on building an endless reviews carousel

Can someone assist me in creating an endless reviews carousel? I've been grappling with it for the past two days. Just so you know, I'm a newcomer to web development and my code may not be the cleanest. Here's the code snippet: <!DOCTYPE ...

Dividing a select option

Looking to transform a single select element into multiple select elements using the separator "/" Here is an example of the original code: <select> <option value="1234">Type 1 / Black</option> <option value="5678">Type 2 / White& ...

After applying sorting, jqGrid displays an empty space below the final row

Having an unusual problem with sorting in the jqGrid. When I sort in descending order, there is extra space below the last row, but when I sort in ascending order, the table ends abruptly at the bottom without allowing any further scrolling. I have includ ...

The `background-size` property in jQuery is not functioning as expected

I am facing the following issue: When I click on a div with absolute positioning, I want to animate its position, width, and height. In addition, I want to change the background-size using jQuery. However, the problem is that all CSS properties are updat ...

Building an electron application with vue js to incorporate static images access

Looking for guidance on linking static images with vuejs in electron. Upon starting the app, I encountered the following response: The structure of my project folder is as follows: to-do-desktop: | |-.electron-vue |-build |-dist |-node_modules |-src --& ...

The issue with Rails and Ajax request failing to load arises when including a .js.erb file

I have a project in mind for a simple website, akin to a stock tracker. One of the key features I'm trying to implement is using ajax to get results without having to reload the entire page. Although I am able to retrieve the HTML with the desired dat ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Is your sticky sidebar getting in the way of your footer?

I've developed a custom sticky sidebar for displaying ads, but I'm facing an issue. When I scroll to the bottom of the page, it overlaps with the footer. Can someone please take a look at this? - var stickySidebar = $('.sticky'); if ...

What is the process for transferring inputted values from a form on one HTML page to variables on another HTML page?

For the website I am currently developing, I have implemented a form on an options page with the following code: <form method="POST" action="process.asp" name="form1"> <table width="70%" border="0" cellspacing="0" cellpadding="0"> ...

Generating a multi-dimensional array from a one-dimensional array - Structuring Data

Looking to create a nested array utilizing the path as a guide for child elements. For example, 4.1 is a child of 4, 4.1.1 is a child of 4.1, and so on. Given a flat array with all data and paths, what's the optimal method to construct a nested array ...

What is the best way to identify the n-th parent element using JavaScript only?

Is there a different way to define the nth parentElement in JavaScript rather than using: var theComment = e.target.parentElement.parentElement.parentElement.parentElement; ...

Encoding a JSON representation of an HTML list where all children are displayed at each parent item

Here is the structured list that I am currently working with: function convert( name_ref ) { name_ref = name_ref + " > ol > li"; var mylist = []; $(name_ref).each(function () { if ($(this).find('> ol > li').length){ myl ...

Adjust the values of a specific field in every document by referencing another field within the same document

Within my database, I store student records that each contain the fields amountOwed and tuition. The task at hand is to update the value of amountOwed to be the sum of its current value and tuition. I am considering utilizing a .find query to retrieve al ...