JordanH
JordanH

Reputation: 139

Convert HTML tags and display as styled text using javascript

I'm looking to design a form that will accept HTML tags and convert them into styled text displayed in a separate text area. Think a very simple JSbin. I thought that this would work:

 document.getElementById('tagName').innerHTML='variable'

But this displays the text along with the tags - I just want the tag.

I need some helpful hints or a nudge in the direction I should go. Thanks!

Upvotes: 0

Views: 1732

Answers (4)

Ele
Ele

Reputation: 33726

I think what you're looking for is contenteditable attr.

You can use that attribute in order to make editable a DOM element like div, span, p, and so on.

For more info go to Making content editable

On the order hand, to be able to write HTML from a textarea and the entered HTML text be rendered into the contenteditable element, you need to bind some kind of event in order to get the wrote HTML and then set it into the target contenteditable element.

var variable = '<b>EleFromStack</b>',
    tagName = document.getElementById('tagName'),
    textarea = document.getElementById('textarea');
    
textarea.addEventListener('input', function() {
  tagName.innerHTML = this.value;  
});
div {
  width: 300px;
  border: 1px dashed #000
}
<textarea id='textarea'>
</textarea>

<div id='tagName' contenteditable='true'>
</div>

Upvotes: 0

William
William

Reputation: 1

The problem is you're trying to write HTML into a text area. The text area is reserved, by the browser engine, to post plain text. Instead of writing out your content to a textarea write it to a DIV or some other content block designed to contain HTML.

Upvotes: 0

Alexandre Senges
Alexandre Senges

Reputation: 1599

I think what you want to do is create an input then listen to the value changes and display the inner html in another div

<!-- HTML -->
<input type="text" id="input"></input>
<div id="output"></div>

Then listen to the change and update the output

//JS
const input = document.querySelector('#input'),
      output = document.querySelector('#output');
button.addEventListener('change', () => {
  output.innerHTML = input.value;
})

(JSBIN: https://jsbin.com/genokox/edit?html,js,console,outputjsbin)

Upvotes: 0

Arleigh Hix
Arleigh Hix

Reputation: 10887

Take a look at https://gomakethings.com/two-ways-to-get-and-set-html-content-with-vanilla-javascript/ you want to use .textContent to get the text without the tags.

document.getElementById('text').innerHTML=document.getElementById('html-elements').textContent
<div id="html-elements">
<button>hello</button> <strong><em>world</em></strong>
</div>
<div id="text"></div>
      

Upvotes: 1

Related Questions