0

Here's what I'm doing:

window.onload = () => {
    const position = document.getElementsByClassName('className')[0];
    const html = 'MULTIPLE LINES OF HTML';
    position.insertAdjacentHTML('afterbegin', html);
};

Currently I've concatenated multiple lines of HTML, which is kinda messy and difficult to work with.

I'd prefer to work with the HTML in an HTML file and just use "const html = index.html" if possible (or something that will help avoid concatenating HTML inside of a variable).

I've tried "const html = index.html" and was expecting it to just use the HTML in the file (this is my first personal project, I'm new to JavaScript, and have no idea what the correct way to do this is, if any).

When I tried this I get an "Uncaught ReferenceError: html is not defined"

*I also tried referencing this question: Assigning an html file to a variable

...and couldn't figure it out still. (I'm new to this so node.js is foreign to me.)

I've been searching for hours and haven't found a solution...

Any help is much appreciated!

futureDev
  • 3
  • 2
  • 1
    Technically it's possible, but such a large string is useless. DOM is for manipulating the document, your current code is on the right tracks. – Teemu Nov 07 '22 at 06:00
  • In a content script you can use `fetch` + [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources). – wOxxOm Nov 07 '22 at 08:46

1 Answers1

0

You cannot assign a HTML file to a JavaScript variable. Rather you can write a block of code in JavaScript and insert them to HTML. Create a div element with an id="wrapper" in HTML file. Add the below code in your JS file.

The simple and safest way to use the concatenation operator (+) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stringify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.

// Storing HTML code block in a variable
var codeBlock = '<div class="content">' +
                '<h1>This is a heading</h1>' +
                '<p>This is a paragraph of text.</p>' +
                '<p><strong>Note:</strong> If you don\'t escape "quotes" 
                properly, it will not work.</p>' +
                '</div>';
// Inserting the code block to wrapper element
document.getElementById("wrapper").innerHTML = codeBlock
node_modules
  • 4,790
  • 6
  • 21
  • 37
  • 3
    It's very possible to assign the content of a HTML file to a JS variable. Also, "safety" and [innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations) don't belong together. – Teemu Nov 07 '22 at 06:45