I'm trying to display HTML from a function


Joined
Jun 14, 2022
Messages
1
Reaction score
0
Hi all,


I have a function that returns HTML and I'm setting a text's innerText to the return value of that function.

It only displays raw code.
 
Ad

Advertisements

Joined
Mar 11, 2022
Messages
82
Reaction score
8
Show a HTML ELEMENT:
Code:
<div id="myElement" style="display:none;">Hello</div>
<button onclick="toggleHello();">Show / Hide Element</button>
<script>
function toggleHello(){
      var myElement=document.getElementById('myElement');
if(myElement.style.display==='none'){myElement.style.display='block';}else{myElement.style.display='none';}
}
</script>
Insert text or HTML into Element
Code:
<div id="myElementB">Default Text</div>
<input type="text" placeholder="New Text" id="newText"><button onclick="setText();">Set Text</button>
<script>
function setText(){
      var myElement=document.getElementById('myElementB');
      var inputField=document.getElementById('newText');
myElement.innerHTML=inputField.value.trim();
}
</script>
 
Ad

Advertisements

Joined
Jan 24, 2022
Messages
30
Reaction score
1
I think we can apply this code here:

function extractContent(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
};

alert(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>"));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top