Reputation: 3864
I have some checkboxes, once I check one of these the ID of the checkbox is sent to a function. I want this function to change the checkbox to a <img>
element with the same ID.
I have tried
document.getElementById(ID).innerHTML = '<img src="image.png" id="' + ID + '"/>';
But this doesn't work, is it possible to change a element or would I need to create a new one using the same ID?
Thanks
Upvotes: 5
Views: 13692
Reputation: 2857
You can try to write like this one. It worked for me. Replace the innerHTML with HTML
document.getElementById(ID).HTML = '<img src="image.png" id="' + ID + '"/>';
Upvotes: 0
Reputation: 6814
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
Upvotes: 2
Reputation: 15221
You'll need to create a new element and remove the old one. In case you need it, here's a quick article on adding and removing elements using javascript: http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
By way of explaining why you can't do what you were trying to do, your elements are represented in the DOM as different "types" (strictly speaking, this is not true, but it's a useful representation), and you can't just change the "type" of an object by changing its underlying markup.
Upvotes: 2
Reputation: 11922
I would advise that rather than replace one element with another you make one visible and one invisible eg...
document.getElementById(ID).style.display='none';
and
document.getElementById(ID).style.display='block';
And I would think of a way round the same ID constraint. Why do you need them to have exactly the same ID?
Upvotes: 3