Ron I Ron I - 6 months ago 9
Javascript Question

Creating and setting a link element in a new html page in a new window

I am trying to accomplish the following and my approach isn't working currently. Hopefully the SO community can help! Thanks in advance.

Goal: user clicks a button on page A and it opens page B and sets page B's link element in the head to point to a css file.

Problem: I get this error in the console:

Uncaught TypeError: Cannot read property 'head' of undefined


Fiddle
https://jsfiddle.net/intelligence_ai/Lx09wxaa/3/

HTML

<div class="container">
<div class="button">
test element
</div>
</div>


Javascript

$('.button').on('click', function() {
let win = window.open;
let link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', '/stylesheets/my.css');
win.document.head.appendChild(link);

});

Answer

You need to execute the window.open function:

let win = window.open(); // Notice the parenthesis

And document.head refers to nothing. Instead, do :

win.document.getElementsByTagName('head')[0].appendChild(link);

https://jsfiddle.net/x5qkg4kq/

If you inspect the source of the new window, you'll see that link tag you created.

Comments