-1

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>
cph
  • 458
  • 2
  • 6
  • 24

2 Answers2

1

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">
&nbsp;
</div>

In the above code jQuery is used only to trigger on document.ready.

Todor Simeonov
  • 806
  • 1
  • 6
  • 11
1

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.

trincot
  • 317,000
  • 35
  • 244
  • 286