Output the 'script' using the `document.write`

Revised inquiry

I am endeavoring to construct two distinct HTML files: main.html and sufler.html. The concept is to manage the sufler.html page from main.html. To achieve this, I have devised a solution where I write the code for sufler.html as a string element on the main.html page. I can then make necessary modifications within that string element and utilize the document.write function from main.html. Everything functions properly except for the <script> function...

main.html

<script type="text/javascript">
var HTMLstringPage1     = '<!DOCTYPE html><html><head><link href="style.css" rel="stylesheet" type="text/css" />',
    HTMLstringPage2     = '</body></html>',
    HTMLstringStyle     = '\x3Cscript type="text/javascript">function style(){document.getElementById("flip").style.font="normal normal 30px sans-serif";}\x3C/script>',
    HTMLstringDiv1      = '</head><body onload="style()"><div id="sufler"><div id="mov"><p id="flip">',
    HTMLstringDiv2      = '</p></div></div>';

var newWindow           = window.open('sufler.html','_blank','toolbar=no, scrollbars=no, resizable=no, height=615,width=815');

    newWindow.document.body.innerHTML = '';
    newWindow.document.write(HTMLstringPage1,HTMLstringDiv1+"Text"+HTMLstringDiv2,HTMLstringPage2); //operational
//  newWindow.document.write(HTMLstringPage1,HTMLstringStyle,HTMLstringDiv1+"Text"+HTMLstringDiv2,HTMLstringPage2);//runs into issue with script function
</script>

Seeking assistance with this matter.

Answer №1

If you want to insert a script tag dynamically, here is a more efficient way to do it:

var newDocument = targetWindow.window.document;
var newScript = newDocument.createElement("script");
newScript.type = "text/javascript";
var newText = newDocument.createTextNode('function changeFont(){document.getElementById("header").style.font="italic bold 20px Arial";}');
newScript.appendChild(newText);
newDocument.getElementsByTagName("head")[0].appendChild(newScript);

You can view a live demo here.


In most cases, creating code on the fly like this is not necessary. Usually, you already have an idea of what the code should do. Instead of generating custom functions dynamically, it's better to create a predefined function that accepts arguments and call it with the right parameters:

function customizeStyle(elementID, newStyle) {
    document.getElementById(elementID).style.font = newStyle;
}

customizeStyle("header", "italic bold 20px Arial");
customizeStyle("footer", "normal normal 12px sans-serif");

Answer №2

Make sure to use regular opening brackets when including <script> tags:

var HTMLstringStyle = '<script type="text/javascript">function styluss(){document.getElementById("flip").style.font="normal normal 30px sans-serif";}<\/script>';

It's hard to imagine a scenario where this would be necessary... appending a <script> tag to either the <head> or <body> element is typically a better 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

Customized content is delivered to every client in real-time through Meteor

I am currently working on creating a multiplayer snake game using three.js and meteor. So far, it allows one player to control one out of the three snakes available. However, there is an issue where players cannot see each other's movements on their s ...

Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed. Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization ...

The attempt to install myapp using npx create-react-app has failed. The installation has been aborted

Attempting to create a new project using npx create-react-app my-app resulted in an error message saying Aborting installation. https://i.sstatic.net/IhpQJ.jpg Initially, I had node v14.17.1 installed. Upgrading to the latest version 16.4.0 did not resol ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...

Tips for integrating Grails ${createLink} into your javascript code

Below is a JavaScript function that I have: function GetSelectedItem() { var e = document.getElementById("country"); var strSel = e.options[e.selectedIndex].value; alert(strSel); var url = "${createLink(controller:'country', act ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

Exploring the intricacies of Node-Craigslist syntax

Greetings! I am currently utilizing the node-craigslist package found at https://github.com/brozeph/node-craigslist and I am in need of assistance with some syntax related to the details method. The documentation provides the following example: client . ...

What is the Extent of Support for JSON?

What level of support does JSON have across different browsers? I recently tested the following: <?php header('Content-type: application/json'); $arr = array('name' => 'Lisa'); echo json_encode($arr); ?> ...

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Having trouble modifying a nested object array within a treeview component in Reactjs

Thanks for your help in advance! Question: I'm having trouble updating a nested object of an array in a treeview using Reactjs. Please refer to the code and sandbox link below: https://codesandbox.io/s/cocky-leakey-ptjt50?file=/src/Family.js Data O ...

define` module root path

Currently, I am working with Typescript and my source files are located in the src directory. After transpiling, Typescript generates the output in the lib folder. This means that when I need to import components from my package, I have to specify the full ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Struggling with the addition of the 'Other' option in React manually. Any tips or suggestions?

I've encountered a slight issue regarding the functionality of my React Component below. Specifically, I want users to have the ability to enter a poll category that is not listed in the select component options by using an input field. This scenario ...

SyntaxError: Identifier was not expected

I am currently working on a function that involves a table of rows with edit buttons. Whenever the edit button is clicked, the following function is called and I encounter this error: Uncaught SyntaxError: Unexpected identifier The error seems to be poin ...

Error encountered in Browserify bundle.js: exec function is not executable

After setting up Node.js, npm, samba-client, and browserify on my system, I encountered a frustrating issue in my bundle.js file. An Uncaught TypeError related to the 'exec' function has been causing trouble, and despite my efforts, I have been u ...

What is the best method for retrieving the complete error message from my client-side Node and Express server?

When I send a request to my express route and it returns a 400 status along with an error message, I am facing an issue on the client-side. The alert message only displays "Object object" instead of the actual error message that I see on the server side. U ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

Is there a way to automatically fill in a text field when an option is chosen from a dropdown menu populated with a list of objects?

When working with a DTO that has attributes id, name, and text, I am creating a list of these DTOs and passing them to my JSP using model.addAttribute. In the JSP, I am rendering a Spring list in the following way: <form:select path="notificationsId" i ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

Detecting collisions in three.js – a comprehensive guide

Currently, I am working with three.js and have incorporated two mesh geometries into my scene. I am looking for a way to detect collisions if these geometries intersect or would intersect when translated. How can I carry out collision detection using thre ...