Home > Mobile >  How to use HTML code present in a string?
How to use HTML code present in a string?

Time:05-16

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>";

CodePudding user response:

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);

CodePudding user response:

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>

CodePudding user response:

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 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");

  • Related