Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically change html element

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

like image 962
Elliott Avatar asked Dec 07 '10 00:12

Elliott


People also ask

Can we change HTML tag dynamically?

The easiest way to modify the content of an HTML element is by using the innerHTML property . The innerHTML property gets or sets the HTML or XML markup contained within the element.

How do I create a dynamic element in HTML?

With document. createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document.

What is dynamic element in HTML?

Dynamic HTML is a set of technologies that allows dynamic changes to HTML documents. • An embedded script can be used to change tag attributes, contents or element style properties. • These changes are not uniformly supported across the full spectrum of browsers.

What is Dynamic HTML with example?

Simple examples of dynamic HTML capabilities include having the color of a text heading change when a user passes a mouse over it and allowing a user to "drag and drop" an image to another place on a Web page. Dynamic HTML can allow Web documents to look and act like desktop applications or multimedia productions.


2 Answers

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?

like image 108
El Ronnoco Avatar answered Oct 04 '22 01:10

El Ronnoco


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.

like image 43
Ender Avatar answered Oct 03 '22 23:10

Ender