简体   繁体   English

如何将现有的DOM元素文本转换为HTML元素?

[英]How do I convert existing DOM element text to HTML element?

I have an element that is already present on the page with HTML as a string. 我有一个已经存在于页面中的元素,其中HTML作为字符串。 How can I take the text from that element and convert it into HTML and re-inject it back into the existing element? 如何从该元素中获取文本并将其转换为HTML,然后将其重新注入到现有元素中?

Everything I try re-renders the elements innerhtml as text. 我尝试的所有内容都会将innerhtml元素重新呈现为文本。

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? 您可以从此处查看如何解码HTML实体: 在Java中取消转义HTML实体?

After that you can inject your code into a given element using .innerHTML property: 之后,您可以使用.innerHTML属性将代码注入给定元素:

 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. 在上面的代码中,jQuery仅用于在document.ready上触发。

You need to read out the textContent instead of the innerHTML , and then write that to innerHTML like you had it: 您需要读出textContent而不是innerHTML ,然后像使用它那样将其写入innerHTML

var element = current_element.previousElementSibling.querySelector('div');
element.innerHTML = element.textContent;

Note also that getElementsByTagName returns a NodeList which does not have innerHTML . 还要注意, getElementsByTagName返回一个不包含innerHTML的NodeList。 Instead use querySelector . 而是使用querySelector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM