Modifying Content in JavaScript-Generated HTML Code -
i trying modify innerhtml of div when clicked. have dynamically generated array of divs, , want access table user has clicked.
i have tried dynamically setting id of tables in javascript code:
(for var i=0;i<array.length;i++){ var idvalue = "foo"; // append table html string. html += "<div onclick='modifyinnerhtml(\"" + idvalue + "\")'>...</div>"; var divs = document.getelementsbytagname('div'); divs[divs.length-1].id=array[i].idvalue; }
then in modifyinnerhtml()
access element id:
function modifyinnerhtml(id){ document.getelementbyid(id).innerhtml+="add update"; }
while think code should work fine, breaking @ document.getelementbyid(id)
function, , realize id of divs not being set dynamically. thoughts on why might or there faster ways this?
thanks in advance!
you'd better use dom manipulation library this, jquery.
as events, jquery let define them in more reliable way. should avoid defining event handlers in attributes anyway, better attach them dom using references elements, or, better yet, jquery elemnt sets.
case 1: generate divs
dynamically event handler set:
for(var = 0; < 10; ++i) { $("<div>") .addclass("clickable-div") .html("click me!") .on("click", function() { $(this).html("you clicked me!"); }) .appendto("body"); }
case 2: add event handler div
s contain class clickable-div
$("div.clickable-div").on("click", function() { $(this).html("you clicked me!"); });
jquery much faster things done you'd write in pure js.
Comments
Post a Comment