0

Let's say I have a HTML string that gets passed to a new window/browser using the following method:

var htmlStr =
        "<div><button id='copy-all'>Copy all contents</button></div>" +
        "<div id='contents-container'>" +
        "    (lots of contents are placed here...) " +
        "</div>"
   , newWin = window.open("", "Test", "width=1000, height=800, scrollbars=1, resizable=1")
   , doc = newWin.document;

doc.write(htmlStr);

As you can see, there will be a button (#copy-all) along with all the contents once the HTML string is passed to the new window and rendered.

The question is - how can I attach a JavaScript function (with or without using jQuery) to the button that enables me to manipulate the DOM placed inside the div (#contents-container) element? I tried including a function literal as part of the htmlStr variable but it doesn't seem to be a viable option.

2
  • like doc.getElementById('copy-all').onclick = function() { alert('hi') };? Commented Jan 19, 2015 at 21:30
  • instead of using .write use .insertAdjacentHTML; Commented Jan 19, 2015 at 21:32

2 Answers 2

2

With jQuery I would do it like this:

$('#copy-all', doc).on('click', function() {
    $('#contents-container', doc).html('test');
});

Here is a working JSFiddle: http://jsfiddle.net/qd8dybg0/2/ (don't forget to disable your popup blocker)

Sign up to request clarification or add additional context in comments.

Comments

1

A variant of Mario A's answer which uses jQuery that does not use jQuery:

doc.getElementById("copy-all").onclick = function(event) {
    doc.getElementById("contents-container").innerHTML = 'test';
};

And a demo JSFiddle (disable popup blocker to see demo): http://jsfiddle.net/kv2p8dwe/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.