Reputation: 1237
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>";
Upvotes: 1
Views: 1027
Reputation: 51
Just Do these steps:
You Need to parse string to html like this:
let myhtml = document.createElement("html");
myhtml.innerHTML = foo;
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");
Upvotes: 0
Reputation: 20934
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);
Upvotes: 2
Reputation: 48
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>
Upvotes: 1