0

How do I return this as string not html element?

<script>
function myFunction() {
  var str = "<input type='text'/>";
  var res = str.toString();
  document.getElementById("demo").innerHTML = res;
}
</script>

This is the return result

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 1
    Using innerText replace innerHTML http://stackoverflow.com/questions/19030742/difference-between-innertext-and-innerhtml-in-javascript – Đô Nguyễn Apr 24 '17 at 02:48
  • 1
    `textContent` *may* be more appropriate - see https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#Differences_from_innerText – Jaromanda X Apr 24 '17 at 02:56
  • Are you trying to return `#demo` element `html` as string? `.toString()` call is not necessary. – guest271314 Apr 24 '17 at 03:00
  • If you're working with XHTML, there should be a space between `'text'` and `/>`. If you are working with HTML, no `/` is needed. – Pyromonk Apr 24 '17 at 03:20

2 Answers2

4

Try textContent instead of innerHTML.

Aurasphere
  • 3,841
  • 12
  • 44
  • 71
taile
  • 2,738
  • 17
  • 29
0

I had use attribute .textContent in javascript to resolve problem. Maybe it will be help a lot.

HTML

<body>
Click button to return a string of input.
<br/>
<button onclick="generate();">Try it</button>
<br/><br/>
<span id="demo"></span>
</body>

Javascript

<script>
function generate() {
    var str = "<input type='text'/>";
    var res = str.toString();
    document.getElementById("demo").textContent = res;
}
</script>

Link for demo:

https://jsfiddle.net/hofvb4ky/1/

Refer from:

https://www.w3schools.com/jsref/prop_node_textcontent.asp

Sinh Bui Dinh
  • 31
  • 1
  • 1
  • 4