简体   繁体   中英

How to access Element created by javascript document.createElement function

I'm creating a div at run-time using java-script document.createElement function.And now i need to execute another function on scrolling of dynamic created div.And also need to catch key-down event of div. Can any one tell me how can i achieve this.

You can do this by calling the scrolling function after the div element is created. Make sure the function is called after the createElement

You need to insert the dynamically created div into the DOM. Without doing that, you cannot retrieve it by using document.getElementById . You can insert your dynamically created div into the element by calling a function like appendChild or insertBefore , described here http://www.w3schools.com/jsref/dom_obj_all.asp

After you find an appropriate place to insert your div into the DOM, you should be able to retrieve it from anywhere by calling document.getElementById("myDivId"); . You'll also need to give that created div an id after creation, if you haven't already done so. The entire thing would look something like:

var myDiv = document.createElement("div");
myDiv.id = "myDivID"; //Give it some ID
var divsParent = document.getElementById("dynamicDivsParentElementID"); //get the element where you want to insert the div into
divsParent.appendChild(myDiv);
var retrievedDynamicDiv = document.getElementById('myDivID');

Check it out working on jsFiddle: http://jsfiddle.net/qnPUF/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM