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

Regular expressions should be utilized in a way that they do not match exactly with a

Can someone help me create a regular expression for an html5 input pattern attribute that excludes specific items? How can I convert ab aba ba into a pattern that will match anything that is not exactly one of these words? For example, I want the fol ...

What occurs in the event of a server crash following the scheduling of a task using cron?

Imagine I set a task to take place at time t2 in the future, where t1 < t2 < t3 If the server crashes at time t1, will the scheduled task still run if the server is restarted before t2 (t1 < t < t2)? What happens if the server crashes at t1 a ...

Arranging grid elements in Material-UI

Currently, I am in the process of transforming a JavaFx window into a web application using React.js & Material Ui. The goal is to replicate the appearance and functionality of the original JavaFx application as closely as possible. The layout of the wind ...

Which CSS properties can I implement to ensure that the text remains legible regardless of the background behind it?

Looking ahead, I am displaying an issue where the colors are almost perfect, but when different percentages are applied, some or all of the text becomes obscured. My goal is to assign the font color based on the background difference. I vaguely remember s ...

Adjust the text color of a particular word as you type using the contenteditable property set to "true"

I'm attempting to jazz things up a bit. For instance, I have a div that is set as contenteditable="true". What I want to achieve is changing the color of a specific word I type while writing. In this case, let's say the word "typing" sh ...

Reloading a webpage does not clear HTML tables containing jQuery interactions in Firefox

Apologies if this question has already been asked. I incorporated hide/unhide features using jQuery into a simple HTML table. The table functioned correctly in Chrome 24.0.1312.52 m and IE8+. Yet, upon refreshing the page in Firefox 15.0.1, the pr ...

Retrieving a database value in Node.js Firestore containing a space

Hello, I'm just getting started with node Js and I anticipate that it will be a smooth ride! Currently working on an application using node JS with Firestore where I need to retrieve data like "display name": James and "Age": 22 Since Age does not h ...

Retrieve the 'current' scope using a 'master' controller

I have a main controller that I refer to as my 'root' controller, which is declared using the ng-controller attribute. Additionally, I have a few other controllers that are created dynamically through a $routeProvider. I want to define a function ...

What is the method to design a file upload feature without a specific form using JavaScript?

I am currently working on a form that handles file uploads using jQuery and AJAX. The goal is to upload the files individually as JSON containing base64 data. Rather than uploading all the images at once, I want each image to be treated as if it were in it ...

Unable to apply CSS modifications to child elements in AngularJS

angular.element($document[0].querySelector("table > tbody > tr")).mouseover().css("background-color", "red"); <table> <thead> <tr> <th>Name</th> < ...

Is the HTML Page loading before the AJAX call is made?

On my HTML Page, I have a button tag that looks like this: <button ng-hide="alreadyFreinds()" type="button" class="btn btn-primary btn-lg">Friend</button> However, when attempting to access certain parts of the alreadyFriends function shown b ...

utilize text offsets to insert tags within strings

I've been facing challenges with using JavaScript string methods and regular expressions. It seems like I might be missing something obvious here. Please forgive me if I'm repeating the question asked by tofutim in more detail, which can be found ...

Adding choices to dropdown menu in AngularJS

As a beginner in AngularJs, I am struggling with appending options to select boxes created by javascript. Below is the code snippet that is causing the issue. var inputElements = $('<div><label style="float:left;">' + i + '</ ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Tips for safeguarding against the insertion of scripts into input fields

Is there a method to stop users from inputting scripts into text fields or text areas? function filter($event) { var regex = /[^a-zA-Z0-9_]/; let match = regex.exec($event.target.value); console.log(match); if (match) { $event.pre ...

Utilizing SCSS to implement custom animations according to specific element IDs

How can I add different animations based on the ID of two DIVs with the same class when clicked? JSX: <div className="card"> <div id="front" className={frontClasses.join(' ')} onClick={clickedFront}> OPEN ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Can you provide me with instructions on how to create a toggle effect for a button using vanilla JavaScript?

Looking for guidance on creating a toggle effect with a button that switches between 2 images. I've managed to get it working with event listeners on btn2 and btn3, but can't seem to implement the 'toggle' effect on btn1. Any insights o ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

Filtering JSON array is just as simple as working with XML

During my project, I have transitioned from using XML format to JSON format. The XML structure includes nodes such as: <Creature> <Name>Someone</Name> <Desert>false</Desert> <Woods>false</Woods> < ...