Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

68
Vistas
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>";
7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

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

7 months ago · Juan Pablo Isaza Denunciar

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>
7 months ago · Juan Pablo Isaza Denunciar

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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos