Troubleshooting CSS appendChild not functioning as anticipated

I'm attempting to manually input CSS for font-face in a new window with the following code:

const css = '@font-face {font-family:Roboto; src:url("assets/fonts/Roboto-Black.ttf");}';
const head = this.externalWindow.document.getElementsByTagName('head')[0];
const style = this.externalWindow.document.createElement('style');
style.type = 'text/css';
style.appendChild(this.externalWindow.document.createTextNode(css));
head.appendChild(style);

However, the CSS doesn't seem to be recognized as such and isn't highlighted in the source code as CSS.

https://i.sstatic.net/RK3QJ.png

On the other hand, when I use document.write to input the style, it works perfectly and loads the font as intended.

this.externalWindow.document.write('<html><head><style>' + '@font-face {font-family:Roboto ;src:url("assets/fonts/Roboto-Black.ttf");}' + '.inner{font-family: Roboto;font-size: 40pt;text-align: justify;}' + '</style></head><body onload="window.print();window.close()"><p class="head">' + this.headContents + '</p> <p class="inner">' + this.innerContents + '</p> <p class="sign">' + this.signContents + '</p></body></html>');

https://i.sstatic.net/bTcmC.png

Answer №1

Follow these steps:

  1. Create an empty <style> element within the externalWindow.document
  2. Access the stylesheet object from the newly created <style> element
  3. Fill the stylesheet object with style rules by using the insertRule method

For instance:

// Add the <style> element to the <head> section of externalWindow.document
const head = this.externalWindow.document.head;
const style = this.externalWindow.document.createElement('style');
head.appendChild(style);


// Obtain the external stylesheet object
const externalStylesheet = style.sheet;


// Add style rules to the external stylesheet
externalStylesheet.insertRule('@font-face {font-family: Roboto; src: url("assets/fonts/Roboto-Black.ttf");}', 0);
externalStylesheet.insertRule('.inner {font-family: Roboto; font-size: 40pt; text-align: justify;}', 1);

Answer №2

.createTextNode operates under the assumption that your content is plain text and will treat it as such, adding necessary escape characters (MDN).

Consider using style.innerHTML = css as an alternative approach.

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

What is the process by which React loads and runs JSX content?

What is the method used to identify and handle JSX code? <script src="src/main.js" type="text/babel"></script> ...

Guide on integrating Select2 with webpack

I recently acquired the select2 node module with this command: npm install select2 After adding it to my app.js: require('select2')($); Although no errors appear when I use webpack, upon opening the application, I encounter: Uncaught TypeEr ...

Counting the occurrence of a specific class within an element using jQuery

Within my table, each row is assigned one or more classes based on its region. This is the structure of my table: <table> <thead> <th>Title</th> <th>Name</th> </thead> <tbody> <tr class="emea ...

Ways to divide a cluster in three.js?

My dilemma involves voxels that require grouping, so I have opted to place them in a container: container.add(e); Next, I integrate the container into the scene. However, I am now faced with the challenge of how to separate the voxels without the need to ...

Is it beneficial to incorporate keys into an express instance for improved functionality?

If I want to pass information from my index.js file to multiple endpoints across different routes, is it sufficient to attach a custom key to the express instance (app)? For instance, if I am using socket.io and want multiple endpoints to emit from the i ...

Guide to adjusting the screen resolution on your iPad 3

Hello everyone, I'm fairly new to designing for the iPad 3. Could someone please provide some guidance on how to set media queries specifically for the iPad 3? Thank you in advance. ...

Why does Drupal's Advagg display several css and js files?

After installing the Advag module, I noticed that it is combining files, but there seems to be an issue: <link type="text/css" rel="stylesheet" href="/sites/default/files/advagg_css/css__sqX0oV0PzZnon4-v--YUWKBX0MY_EglamExp-1FI654__IOPiOtulrIZqqAM0BdQC ...

Guide on extracting unique identifiers from an array of objects and sorting them by the earliest date in JavaScript

I've got an array of objects and I'm looking to retrieve the items with unique IDs while also selecting the earliest date. For example: [{id:1, date: Jan 12}, {id:2, date: Feb 8}, {id:3, date: Feb 8}] var array = [{id: 1, date: Jan 12 2021 08:00 ...

Leveraging jQuery to implement onclick functionality within a Jinja2 loop

I'm currently working with Python, Flask, and Jinja2. When using a for loop, I want to be able to click on the {{ place.place_photo }} element to toggle its details. Initially, I had it functioning correctly but ran into an issue where clicking on on ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

Validating decimals in a text field with either JavaScript or jQuery

I need to implement text field validation on the keyup event. The text field should only accept money type decimals such as: (12.23) (.23) (0.26) (5.09) (6.00) If any incorrect value is entered, it should revert back to the previous value and remove the ...

What are some ways to modify attributes in a jQuery datatable?

Upon loading the page, I initially set serverside to false. However, under certain conditions, I need to change serverside to true without altering any other attributes. For example: $(tableID).DataTable({ serverSide : false; }); Changing it to: $(t ...

The functionality ceases to operate properly once a new element has been added

I am encountering an issue with the "click" action on a newly created element through a jQuery function, as it is not functioning properly. To demonstrate this problem, I have set up a JSFiddle at the following link (JSFiddle), however, please note that t ...

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

The function causes an unexpected alteration in the coordinates of polygons on a leaflet map

I have been working on enhancing the functionality of a leaflet map by adding triangles with specific rotations to each marker that is created. The code snippet below demonstrates how I achieve this: function add_items_to_map( to_map, longitude, latitude, ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

Execute function when button is clicked in ExpressJS

I am looking to execute a function on my node server when a button on my website is clicked: What I currently have: Index.html (I have not included the entire content for simplicity) <button id="tv">tv</button> Client.js (Client side) const ...

Click on ng-click to sort through the blog entries

Currently, I am in the process of developing a blog utilizing AngularJS and JSON. Nearly everything is functioning as expected except for one particular filter item. As I am relatively new to Angular, it presents a bit of a challenge for me. The issue ari ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...

mention a particular anchor by clicking on it to refresh the webpage

Can a webpage automatically navigate to a specific anchor/tag when reloaded in the browser? Thanks in advance I came across this method: window.location.reload(); However, I'm searching for a solution that can detect the reload and then run a basi ...