Dynamically change html element

I have some flags, as soon as I check one of them, the flag identifier is sent to the function. I want this function to change the checkbox to an <img> element with the same identifier.

I tried

 document.getElementById(ID).innerHTML = '<img src="image.png" id="' + ID + '"/>'; 

But this does not work, is it possible to change the item or do I need to create a new one using the same ID?

thanks

+4
source share
4 answers

I would advise instead of replacing one element with another, you make one visible and one invisible, for example ...

 document.getElementById(ID).style.display='none'; 

and

 document.getElementById(ID).style.display='block'; 

And I would think of the same identifier restriction. Why do you need to have the same identifier?

+3
source

in pure javascript you can do something like:

 function changeToImage(el) { var img = document.createElement('img'); img.setAttribute('src', 'http://www.google.com/images/nav_logo29.png'); img.setAttribute('ID', el.getAttribute('id')); var parent = el.parentNode; parent.appendChild(img); parent.removeChild(el); } 

then from your html you would do

 <input type="checkbox" onclick="changeToImage(this)" /> 

note that this may not be cross-browser proof .... you can also use jquery to simplify things

+2
source

You will need to create a new item and delete the old one. In case you need it, here you will find a short article on adding and removing elements using javascript: http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/

To explain why you cannot do what you tried to do, your elements are represented in the DOM as different "types" (strictly speaking, this is not true, but it is a useful representation), and you cannot just change the "type" of an object by changing it basic markup.

+2
source

You can try to write, like this one. He worked for me. Deploy innerHTML with HTML

document.getElementById (ID) .HTML = '';

0
source

All Articles