Customizing text appearance with innerHTML in JavaScript: A guide to styling

Below is the code I have for a header:

<div id="title-text">
    The Cuttlefisher Paradise
</div>
<div id="choices">
    <ul>
        <li id="home"><a href="#">Home</a></li>
        <li id="contact"><a href="#">Contact</a></li>
        <li id="about"><a href="#">About</a></li>
        <!-- 5 more items -->
    </ul>
</div>

I need to use this as the header on around 10 different web pages, but without using <frame> or <iframe>. It's important for graphical reasons.

Currently, I am using

document.getElementById("home").setAttribute("class", "active")
to style the active tab. However, when the header (the block of code above) is inserted into a div using innerHTML, document.getElementById doesn't work and returns null.

Is there a simple method to include the header on multiple pages without <frame> or <iframe>, or to make document.getElementById identify ids inserted with innerHTML?

Answer №1

Combining all the content into a single JavaScript string and ensuring the correct quoting and line breaks are in place to create a valid JavaScript string will allow you to assign it to innerHTML without any issues. The browser will then parse all the tags and generate the HTML for you.

To see this in action, check out this working example: http://jsfiddle.net/jfriend00/QmGvF/.

The JavaScript code executed from the page ready handler:

var newHTML = '<div id="title-text"> \
    The Cuttlefisher Paradise \
</div> \
<div id="choices"> \
    <ul> \
        <li id="home"><a href="#">Home</a></li> \
        <li id="contact"><a href="#">Contact</a></li> \
        <li id="about"><a href="#">About</a></li> \
        <!-- 5 more items --> \
    </ul> \
</div>';

document.getElementById("top").innerHTML = newHTML;

var home = document.getElementById("home");
home.style.backgroundColor = "#FF0000";

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

How can I keep dragging objects on Raphael JS Freetransform without showing the handles?

Hey there! Currently, I am immersed in a new project that hinges on the utilization of Raphael JS alongside the Raphael.Freetransform plugin. The plugin has been performing admirably with smooth transitions so far. Nonetheless, upon utilizing the hideHandl ...

Unresponsive CSS styles on a specific DIV element

Here is the HTML code I am currently working with: <body> <section id="info"> <div class="status"> ... I have been attempting to apply styles to the div with a class of 'status' using my CSS file linke ...

What causes my slider to speed up with an increase in items and slow down with fewer items in bxslider?

Find more information here jQuery('.homepage_slider').bxSlider( { minSlides: 1, maxSlides: 4, slideWidth: 200, slideMargin: 30, ...

Transforming screen recording video chunks from blob into multipart for transmission via Api as a multipart

Seeking guidance in Angular 8 - looking for advice on converting screen recorded video chunks or blogs into a multipart format to send files via API (API only accepts multipart). Thank you in advance! ...

Building personalized error messages using graphql-js and express

It has come to my attention that you have the ability to create customized errors within graphql and graphql-express. https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb I recently implemented a custom Error feature, but it see ...

Develop a distinctive JavaScript solution that enables an image to appear in fullscreen upon loading the page, and then smoothly fade away after precisely

I have been trying to incorporate a feature on my Shopify frontage website where our logo appears fullscreen and then fades away or disappears after a few seconds, allowing people to access the rest of the website. However, I am facing difficulty in making ...

Issues with the CSS in our unique eBay template are creating some challenges

Our team is currently in the process of creating a customized template for our eBay listings. eBay provides users with the option to upload a description as HTML code and allows the code to link external CSS files. When uploading HTML code on eBay, it ap ...

Enhancing Performance of D3 JS for Visualizing Large XML Data

I am working on visualizing a large XML file, almost 1 GB in size, as a graph of nodes and links using D3 Javascript. I am currently working with mac 10.5.8. I have successfully extracted the content of the file, displaying it as: [Object Element]. The p ...

Adding HTML elements to a Vue Tooltip

Does anyone know how to implement a tooltip in Vue for a table cell that has more than 22 characters in its content? I was looking into using the v-tooltip library (https://www.npmjs.com/package/v-tooltip) Setting the tooltip's content with a simple ...

I'm experiencing an issue where my drum app element does not refresh after performing an action dispatch

Struggling with my React/Redux drum app, I'm at a roadblock with the final component that should update with the selected object's ID through an action dispatch. It baffles me why the element won't reflect the changes even though I've c ...

If the div is visible in the viewport, then automatically scroll to the top

Struggling to locate online resources for this particular technique. In my JSFiddle, users can navigate through fullscreen divs using 'next' or 'prev', as well as scrolling to access the next or previous divs. The issue arises when us ...

What methods does Angular use to handle bounded values?

Consider this straightforward Angular snippet: <input type="text" ng-model="name" /> <p>Hello {{name}}</p> When entering the text <script>document.write("Hello World!");</script>, it appears to be displayed as is without bei ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

I'm having trouble executing the JavaScript function

function contentChange(){ var paragraphs = document.getElementsByTagName("p"); for(var i = 0 ; i < paragraphs.length ; i++){ paragraphs[i].innerHTML = "hello" ;}} contentChange(); I'm struggling to change the content of all ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

What is the best way to showcase additional fields from a custom post type along with the featured thumbnail feature?

'I designed a custom post plugin in Wordpress that successfully displays the title and main content, but I am facing issues with displaying other fields such as company details. Despite mentioning a featured thumbnail option in my plugin, I am not ab ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

Bidirectional binding in Angular 2 Custom Directive

I've been working on a custom directive that automatically selects all options when the user chooses "All" from a dropdown. While I was able to get my custom directive to select all options, it doesn't update the model on the consuming component. ...

Steps for Integrating a Web Service Reference in NodeJS

Can a Web reference be added to a NodeJS project similar to how it's done in .NET framework Web API Projects? Essentially, the NodeJS API project will serve as a middleware between the Front End and an XML Web service. The XML Web service is a secure ...

The validation error occurred with the expectation of a primitive boolean value

My starting point: I'm completely new to using booleans as a beginner developer snippet of code: const { SlashCommandBuilder, PermissionFlagsBits, PermissionsBitField, EmbedBuilder, } = require("discord.js"); const { ...