-1

Can I convert a string to HTML in javascript?

let description = "<a className="peoplelink" id="ether">Ether</a> // is render as 'the historian of the'";

     let html= // I know that it is easy to do with jquery by using .html() method, but can we convert a string to HTML in javascript?
4
  • What's the goal ? What have you tried Commented Jan 11, 2018 at 8:18
  • Use single quotes instead of double quotes to wrap around the string, let foo = '<img src="..." />'; Commented Jan 11, 2018 at 8:20
  • better to use backtick Commented Jan 11, 2018 at 8:21
  • @Weedoze I want to convert string to html like this : <a className="peoplelink" id="ether">Ether</a> is the historian of the <a className="peoplelink" id="jaredites">Jaredites</a>. I am react js developer and I want to change string to html without used jquery. Commented Jan 11, 2018 at 10:14

1 Answer 1

3

Nothing to convert, is a simple string to innerHtml:

I.E.:

const markup = `
 <div class="person">
    <h2>
        ${person.name}
    </h2>
    <p class="location">${person.location}</p>
    <p class="bio">${person.bio}</p>
 </div>
`;

document.body.innerHTML = markup;
Sign up to request clarification or add additional context in comments.

5 Comments

A good answer should explain why the OP has their issue and how your code fixes it.
@mose Raguzzini after using your solution, I have found <a classname="peoplelink" onclick="{this.demoButton}" id="moroni2">Moroni</a> and please see that this is not pure html
Please share a snippet I assure it renders pure HTML
before converting(it is simple string) The record eventually reaches <a className="peoplelink" onClick={this.demoButton} id="moroni2">Moroni</a>, who again translates it and adds his synopsis to <a className="peoplelink" onClick={this.demoButton} id="mormon2">his father</a>’s record { after converting} The record eventually reaches <a classname="peoplelink" onclick="{this.demoButton}" id="moroni2">Moroni</a>, who again translates it and adds his synopsis to <a classname="peoplelink" onclick="{this.demoButton}" id="mormon2">his father</a>’s record this is browser html
Did you miss the string interpolation with backtick (´´) ${variable}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.