javascript - Adding an Image to DOM Dynamically Using Range.insertNode() -


how can dynamically insert img element dom using range.insertnode() ?

my html:

<div class="css_class_for_div" style="height: 250px;" contenteditable="true">     <img src="/path/to/my/image/myimage.png" alt="/myimage.png" title="/myimage.png" class="css_class_for_image" e_resid="/myimage.png" />     <br />     <br />     <span class="css_class_for_span"></span> </div> <input id="mybutton" type="button" value="insert image" /> 

my js:

var button = document.getelementbyid("mybutton"); button.addeventlistener("click", function(e){     var src = "/path/to/my/other/image/image2.png";     var title = "/image2.png";     var cssclassname = "css_class_for_image";     var list = document.getelementsbyclassname("css_class_for_div");     var el = list[0];     var selranges = el.getselection();     if (selranges.rangecount > 0) {         var currange = selranges.getrangeat(0); // range object         if (currange.tostring().length == 0) {             var imagenode = document.createelement('img');             imagenode.src = src;             imagenode.alt = title;             imagenode.title = title;             imagenode.classname = cssclassname;             currange.insertnode(imagenode);         }     } },false); 

[link fiddle]

the above code doesn't work. appreciated.

if want insert image2 first occurrence of div classname = css_class_for_div using range.insertnode(), can use following code.

i had use

var range = document.createrange(); range.selectnode(your div); range.insertnode(your image); 

updated fiddle

var button = document.getelementbyid("mybutton"); button.addeventlistener("click", function (e) {     debugger;     var range = document.createrange();     var list = document.getelementsbyclassname("css_class_for_div");     if (list.length > 0) {         var el = list[0];         range.selectnode(el);         var imagenode = getimagenode();         range.insertnode(imagenode);     } }, false);  function getimagenode() {     var src = "/path/to/my/other/image/image2.png";     var title = "/image2.png";     var cssclassname = "css_class_for_image";     var imagenode = document.createelement('img');     imagenode.src = src;     imagenode.alt = title;     imagenode.title = title;     imagenode.classname = cssclassname;     return imagenode; } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -