Ron I
Ron I

Reputation: 4250

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);

   });

Upvotes: 0

Views: 34

Answers (1)

blex
blex

Reputation: 25659

You need to execute the window.open function:

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

https://jsfiddle.net/tndnt36z/

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

Upvotes: 2

Related Questions