Search code examples
javascriptinnerhtml

JavaScript - Why is innerHTML property displaying as text when it contains HTML?


I have the following bit of JS code being executed in a ASP.CORE View which is intended to basically set the content of an element on the page.

if (notificationBanner) {
    var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
    console.log(bannerText);
    notificationBanner.innerHTML = bannerText;
}

The following is being logged in browser console:

<p>A One Time Password (OTP) has been sent to your mobile number below. Enter the OTP in the field below. <strong>The OTP is valid for 10 minutes</strong>.</p>


And the element ends up like this:

enter image description here

However this is not correct, I want the part in <strong></strong> to be bold. Why is it adding it as text?


Solution

  • I was looking for a vanilla JS solution so looking at the post crayon provided. Found a good solution. Thanks for your help.

    function decodeHtml(html) {
        var txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    }
    
    if (notificationBanner) {
        var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
        console.log(bannerText);
        notificationBanner.innerHTML = decodeHtml(bannerText);
    }