Home > Net >  How to find element in string by class using JavaScipt?
How to find element in string by class using JavaScipt?

Time:04-14

For example I have a string with html code.

const string = `
  <div>
    <h1>Title</h1>
    <h2>Subtitle</h2>
    <div >text</div>
  </div>
`;

Expected result with JS script:

<div >text</div>

How it's possible to do it without jquery and other libraries/frameworks ?

CodePudding user response:

Try this

const string = `
  <div>
    <h1>Title</h1>
    <h2>Subtitle</h2>
    <div >text</div>
  </div>
`;
let arr  = string.split('\n');
for(let i=0; i<arr.length; i  ){ 
    if(arr[i].search("find-me") != -1){ 
        console.log(arr[i]);
     }
}

CodePudding user response:

you can create a temporary element and attach the string using innerHTML:

let tempElement = document.createElement("div");
tempElement.innerHTML = string;
const myElement = tempElement.querySelector(".find-me");

  • Related