1

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>";
4
  • What do you mean with using it? And where? In the browser, in nodejs or somewhere else? Commented May 15, 2022 at 14:30
  • do you need to extract class and id from those elements without knowing their values? as in, class could be myClass, anotherClass, and so on? Commented May 15, 2022 at 14:32
  • I mean I want to use this HTML code somewhere else that is getting passed through a variable Commented May 15, 2022 at 14:32
  • 1
    Keep in mind that this way of executing code have security issues. Commented May 15, 2022 at 14:38

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This approach looks quite simple. Thank you for the response :)
1

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>

1 Comment

Thank you for the response. This is something new for me. I will try this.
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");

1 Comment

Thank you for the response but I don't want to create a new html element for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.