I have an element that is already present on the page with HTML as a string. How can I take the text from that element and convert it into HTML and re-inject it back into the existing element?
Everything I try re-renders the elements innerhtml as text.
window.current_element_content=window.current_element.previousElementSibling.innerHTML;
window.current_element.previousElementSibling.getElementsByTagName('div').innerHTML = window.current_element_content;
Example of the text when printed on the console.
<tr>
<td headers="mon">
9:00 AM - 4:00 PM
</td>
<td headers="tues">
9:00 AM - 4:00 PM
</td>
<td headers="wed">
9:00 AM - 4:00 PM
</td>
<td headers="thurs">
9:00 AM - 4:00 PM
</td>
<td headers="fri">
9:00 AM - 4:00 PM
</td>
<td headers="sat">
Closed
</td>
<td headers="sun">
Closed
</td>
You can see how to decode HTML entities from here: Unescape HTML entities in Javascript?
After that you can inject your code into a given element using .innerHTML
property:
function htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } $(document).ready(function(){ var s = '<input type=button value="Inserted Button">'; document.getElementById('my_place').innerHTML = htmlDecode(s); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div id="my_place"> </div>
In the above code jQuery is used only to trigger on document.ready.
You need to read out the textContent
instead of the innerHTML
, and then write that to innerHTML
like you had it:
var element = current_element.previousElementSibling.querySelector('div');
element.innerHTML = element.textContent;
Note also that getElementsByTagName
returns a NodeList which does not have innerHTML
. Instead use querySelector
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.