-1

For example I have a string with html code.

const string = `
  <div>
    <h1>Title</h1>
    <h2>Subtitle</h2>
    <div class="find-me">text</div>
  </div>
`;

Expected result with JS script:

<div class="find-me">text</div>

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

  • You should propably look at https://stackoverflow.com/questions/3813294/how-to-get-element-by-innertext. – Jip Helsen Apr 13 '22 at 13:56
  • Welcome to [so]! Please take the [tour], visit the [help] and read up on [asking good questions](https://stackoverflow.com/help/asking). After doing some research and [searching](https://stackoverflow.com/help/searching) for related topics on SO, try it yourself. If you're stuck, post a [mcve] of your attempt and note exactly where you're stuck. People will be glad to help. – Scott Sauyet Apr 13 '22 at 13:57
  • @JipHelsen It works with HTML page, but I need to find in in the javascript string. – wefwe fwefwef Apr 13 '22 at 13:59
  • 1
    What are you doing with `string`? Are you adding it to the DOM? – Andy Apr 13 '22 at 14:01
  • @wefwefwefwef well aware of that. You could A) use a library for a regex solution or B) render the string in a mockup DOM. – Jip Helsen Apr 13 '22 at 14:01
  • @Andy No, I need to add only element what I want to find in this string. – wefwe fwefwef Apr 13 '22 at 14:06

2 Answers2

1

Try this

const string = `
  <div>
    <h1>Title</h1>
    <h2>Subtitle</h2>
    <div class="find-me">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]);
     }
}
  • Good solution, but what to do if it doesn't have white spaces? `const string =

    Title

    Subtitle

    text
    ;`
    – wefwe fwefwef Apr 13 '22 at 14:19
  • I've changed arr.length/arr[i] into string.length/string[i] but it doesn't work. I guess it stop where is condition. Could you provide an example? – wefwe fwefwef Apr 13 '22 at 14:27
0

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");
  • 1
    Use this with care, as it may allow unwanted code execution. It is not recommended to use this. -- Example: ``let string = ``;`` – Christopher Apr 13 '22 at 14:31
  • @Christopher is there any way to manipulate html without attaching to DOM ? –  Apr 13 '22 at 14:34
  • 2
    You can make us of the [DOMParser API](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser). This [fiddle](https://jsfiddle.net/8h70moax/) might give you an idea of how to use it. – Christopher Apr 13 '22 at 14:54