Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying different styles in substrings of strings containing html tags

Tags:

html

css

I wanted to capture the user's text-input in a variable USER_INPUT and use the value of that variable as a substring of a multi-styled string that is shown in some DISPLAY div. But there were problems with text-inputs containing html tags, like <div>, as in the following example, where the value of USER_INPUT does not appear at all in DISPLAY, which is understandable, due to the different nature of the .innerText and .innerHTML properties.

var USER_INPUT = "<div>";
      
document.getElementById("DISPLAY").innerHTML =  
       "<span style='color:red'>" + "User Input : " + "</span>" + 
       "<span style='color:blue'>" + USER_INPUT + "</span>";

So after much experimentation, a solution appeared which seems to work well in all cases:

var USER_INPUT = "<div>";
    
var XDIV = document.createElement("div");
XDIV.innerText = USER_INPUT;
var A = XDIV.innerHTML;
    
document.getElementById("DISPLAY").innerHTML =  
       "<span style='color:red'>" + "User Input : " + "</span>" + 
       "<span style='color:blue'>" + A + "</span>";

The above code shows in the DISPLAY: enter image description here which is exactly what I need, that is, to be able to style the user-input independently of the first part of the string.

My problem is that I cannot understand why the above code solves the problem. If the user-input string is passed in a new div as innerText and retrieved as innerHTML, then it miraculously appears correctly in the DISPLAY. I would like to understand the rationale behind this behavior, so any help would be greatly appreciated. fiddle here

like image 758
exp8j Avatar asked Jan 01 '26 20:01

exp8j


1 Answers

Property innerHTML returns or accepts a serialized HTML or XML.

document.getElementById("my-id").innerHTML = "<p>Foo <strong>bar</strong> baz.</p>"

will display "Foo bar baz." as a text.

If you want to display HTML tags you need to escape < to &lt and > to &gt to get &lt;p&gt;Foo &lt;strong&gt;bar&lt;/strong&gt; baz.&lt;/p&gt;

You can use this function to do it (taken from this answer):

function escapeHTML(html) {
    return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
}
like image 152
mx0 Avatar answered Jan 03 '26 10:01

mx0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!