Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
How to use HTML code present in a string?

I am working on something where I want to use this HTML code that is present in a string variable after passing it to some other function.

var foo = "<html><body><div class='myClass'><div id='myId'>Hello World!!</div></div></body></html>";
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use the DOMParser API to turn your string into a document object.

const data = "<html><body><div class='myClass'><div id='myId'>Hello World!!</div></div></body></html>";

const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');

const myClass = doc.querySelector('.myClass');
const myId = doc.querySelector('#myId');

console.log(myClass, myId);

about 4 years ago · Juan Pablo Isaza Report

0

You can use cheerio.js in this case.

var cheerio = require('cheerio');

var foo = "<html><body><div class='myClass'><div id='myId'>Hello World!!</div></div></body></html>"
const $ = cheerio.load(foo);

$('div#myId').text('Hello there!');
$('div#myId').addClass('newClass');

$.html();
//=> <html><body><div class='myClass'><div id='myId'>Hello World!!</div></div></body></html>
about 4 years ago · Juan Pablo Isaza Report

0

Just Do these steps:

  1. You Need to parse string to html like this:

    let myhtml = document.createElement("html");
    myhtml.innerHTML = foo;
    
  2. After you parsed you html you can do what you want. Like if you want to class="myClass" element than you can do like this:

    const myelement1 = myhtml.querySelector(".myClass");

    Similarly if you want id = "myid" element than you can do like this:

    const myelement2 = myhtml.querySelector("#myid");

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!