-1

When I try to display a string with '<' symbol in it, the part of string after the symbol gets ignored. However, when I log it in console it's displayed correctly. Here's a snippet of the issue:

console.log('display<hide');//Displays Full text
document.getElementById('somediv').innerHTML='display<hide';//Removes remaining part
<div id="somediv">
        
</div>

Why does this happen?

Edit:

I am aware about &lt and &gt in HTML, but my question is regarding the issue in displaying < as I had no issues displaying > with innerHTML

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
Shardul Birje
  • 341
  • 5
  • 14

2 Answers2

3

Switch to innerText:

document.getElementById('somediv').innerText='display<hide';

< and > are reserved characters in HTML for tags.

thab
  • 666
  • 1
  • 6
  • 14
2

The opening bracket in your string is parsed as malformed HTML then <hide gets ignored: so either you use .textContent instead of .innerHTML or you change the < character into its HTML entity &lt;

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177