2 posts tagged “dom”
So Im working on this other project now and I am faced with the following situation:
- A server script renders an element's onclick handler as calling a function with an array as its parameter, e.g.
<div onclick="some_function(this, new Array('1','2','3'));">Some content</div> - Everytime some_function() is called, it needs to create another div after it but with the array altered, i.e.
<div onclick="some_function(this, new Array('1','2','3'));">Some content</div>
<div onclick="some_function(this, new Array('2','3'));">Content generated by some_function()</div> - Eventually, the array has no elements left and what I want left is:
<div onclick="some_function(this, new Array('1','2','3'));">Some content</div>
<div onclick="some_function(this, new Array('2','3'));">Content generated by some_function()</div>
<div onclick="some_function(this, new Array('3'));">Second content generated by some_function()</div>
<div>Last content generated by some_function()</div> - What does some_function() look like?
- "onclick" is not a DOM attribute, so you can't assign it a string like:
divElement.setAttribute("onclick", some_function_string);
Actually this does work in Firefox 2 but it may not work in other browsers (and thats the way it should be). - To assign an onclick handler, you specify a function not a string, i.e.
divElement.onclick = function() { some_function(this, new Array('1','2','3')); };
- Convert the function into a string, i.e. (in this case the function I'm interested in is the onclick handler of the divElement)
var onclick_string = divElement.onclick.toString; - Modify the string via string functions and regex (in this case I want to change the array being passed to some_function()):
// Set value to "1", "2", or "3" depending on which one we want to remove
var re_value = new RegExp("[\"']"+value+"[\"'][,]*");
onclick_string = onclick_string.replace(re_value, ""); - Modify the string to exclude everything but the function body:
onclick_text = onclick_text.replace(/[^{]*?{/, ""); // delete everything before and including first "{"
onclick_text = onclick_text.replace(/}[^}]*$/, ""); // delete everything after and including last "}" - Create a new Function object with the string as its body:
var new_onclick = new Function(onclick_text); - Now we have a modified function ready to be used!!
newDivElement.onclick = new_onclick;
- Convert the function to a string
- Do string manipulation to edit the function
- Convert the string back to a function
Arrggh... Ive spent the past four hours fixing my standards-compliant layout to fit to IE6's needs. And from this ridiculous layout:
All I have now is just:
In other words, the top part is done. Im fixing the CSS by setting display: none to all major containers and then work my way down the DOM tree; slowly fixing each <div> one at a time.
Onwards!