What you are trying to do is build a dynamic web page. While this should be left moreso to PHP (PHP Hypertext Processor, a serverside scripting language widely supported by multiple web servers), there is a solution in javascript.
There are multiple solutions to this problem, but I will give you the barebone basics of what you will need to do in order to achieve this.
The first thing that you need to do is make the button have a onclick
attribute set. You can do this like so:
var button=document.createElement("BUTTON");
button.setAttribute("onclick","yourFunction()"); //Function Definition will go here.
This will make it so your button will have functionality when added to the document.
Next, you must actually create the function. I assume that you want one of two things:
- A set function, which would be already created for the environment in which it is used, or
- A dynamic function, one that would be different based on the caller.
I will give a small example of each.
For the set function:
var button=document.createElement("BUTTON");
button.onclick = function(){
//Event handling code.
};
For the dynamic function (A little more effort):
//...FUNCTION...//
function bFunc(/*parameters*/){
/*Code (Using Parameters)*/
}
//...BUTTON...//
var button=document.createElement("BUTTON");
button.onclick = function(){
bFunc(/*Any parameters needed*/);
};
And then add the button to the span:
var spans = document.getElementsByTagName("span"); //CREATE ARRAY OF ALL SPANS
for(var i = 0; i < spans.length; i++){
spans[i].appendChild(button); //APPEND THE BUTTON TO EACH SPAN
}