I have a problem with replacing html elements.
For example, here is a table:
<table> <tr> <td id="idTABLE">0</td> <td>END</td> </tr> </table>
(it can be div, span, anything)
And string in JavaScript:
var str = '<td>1</td><td>2</td>';
(It can be anything, 123 text
, <span>123 element</span> 456
or <tr><td>123</td>
or anything)
How can I replace element idTABLE
with str
?
So:
<table> <tr> <td id="idTABLE">0</td> <td>END</td> </tr> </table>
Becomes:
<table> <tr> <td>1</td> <td>2</td> <td>END</td> </tr> </table> <!-- str = '<td>1</td><td>2</td>'; --> <table> <tr> 123 text <td>END</td> </tr> </table> <!-- str = '123 text' --> <table> <tr> <td>123</td> <td>END</td> </tr> </table> <!-- str = '<td>123</td>' -->
I tried createElement
, replaceChild
, cloneNode
, but with no result at all =(
Use the textContent property to change the text of an element, e.g. element. textContent = 'New text' . The textContent property will set the text of the element to the provided string, replacing any of the existing content.
To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
As the Jquery replaceWith() code was too bulky, tricky and complicated, here's my own solution. =)
The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.
Here is the code
var str = '<a href="http://www.com">item to replace</a>'; //it can be anything var Obj = document.getElementById('TargetObject'); //any element to be fully replaced if(Obj.outerHTML) { //if outerHTML is supported Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var } else { //if outerHTML is not supported, there is a weird but crossbrowsered trick var tmpObj=document.createElement("div"); tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->'; ObjParent=Obj.parentNode; //Okey, element should be parented ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str); }
That's all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With