简体   繁体   中英

Covert html in javascript to HTML tags

I'm working on the tooltips and from the backend I'll get data in with html tags. I need to show in the tooltip with its corresponding data in its respective tags. For example, I'll get hello user click here from the backend. I've to show as hello user in h1 format and click here should be a anchor. I tried with both functions and replace its not working.

With function:

<h1 id="data">

</h1>
    function convertToPlain(html){
        var tempDivElement = document.createElement("div");
        tempDivElement.innerHTML = html;
        return tempDivElement.textContent || tempDivElement.innerText || "";
    }
    var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a> click here<a></p></div>";
    let dataVal = convertToPlain(htmlString)
    document.getElementById("demo").innerHTML = dataVal;

With replace:

https://codesandbox.io/s/serene-fast-u8fie?file=/App.svelte

Are you looking for below result? I made below snippet by copy-paste your code and just update return statement inside convertToPlain function, also I added href attribute to <a> in the htmlString content.

 function convertToPlain(html) { var tempDivElement = document.createElement("div"); tempDivElement.innerHTML = html; return tempDivElement.innerHTML; } var htmlString = "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute<a href='#'> click here<a></p></div>"; let dataVal = convertToPlain(htmlString) document.getElementById("demo").innerHTML = dataVal;
 <h1 id="demo"></h1>

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.

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