tags:

views:

40

answers:

1

Lets say that I have a element reference obtained ala...

var x=document.getElementById("ID123");

Now I want to include some function of x on a dynamically created html element ala...

myWin.document.write("<input  type='button'   data-doit=????? value='Do It'   onclick='window.doit(?????);'/>");

so that function doit() can recreate the original reference x

function doit()
{
var x = ?????;
}

Right now I'm doing this by obtaining a numeric index of x as found via getElementsByTagName and passing that as a parameter to doit().

Is there some way to do this?

A: 

I would probably pass the ID of x to doit(), which would require doit() to look something like this:

function doit(id) {
    var x = document.getElementById(id);
    // etc
}

As far as creating the input element goes, there a couple of ways to do this. This is similar to your current solution (but non-standard):

myWin.document.write('<input ... onclick="doit(' + x.id + ');" />');

The standard solution is to create your new input element using the DOM API:

var input = myWin.document.createElement('input');
input.type = 'button';
// other properties
input.onclick = function () {
    doit(x.id);
};
// insert new element
document.getElementById("myform").appendChild(input);

(Note that inserting the element is a little more complicated in this situation - you have to programmatically find its location in the DOM).

Finally, if you're using jQuery, you might do something this:

var input = $('<input type="button" etc />').click(function () {
    doit(x.id);
});
$('#myform').append(input);
harto
Ok, that's a bit more elegant and simpler than I had been doing but I'll have to go back and add ids to the elements in question. I do have a further question re ids. I understand they should be unique. But unique within what scope? A particular window? document? frameset? If I create a window ala document.write, then come back later a recreate again using document.write, can the ids for the two pages overlap?
Mike D
I don't quite get the line document.getElementById("myform").appendChild(input);I see input is associated with myWin but shouldn't the document reference also be to myWin? I do want to put the button in a new page. And this presupposes the existence of an element with ID "myform"? Could that be the body tag?
Mike D
Hi Mike. I was assuming you already had IDs assigned to the relevant elements from the snippet in your question (`var x=document.getElementById("ID123");`). As far as uniqueness goes, my understanding is that they must be unique within a document.
harto
Regarding your second comment, yes, you're right, that line should also reference the same window/document that `input` was created in. "myform" was just an example ID - you could indeed append directly the `body` or any other element you can get a reference to.
harto