Search code examples
javascriptvariablesextractinnerhtml

Extract specific HTML container from Javascript variable


How would you extract specific html from JS variable that contains html content.

In the example below the JS variable contains the entire html content that was returned from a Fetch API request. I want to just extract the content from the section with class content.

The Variable

const aVariable = fetch(...etc.. etc.. // the returned value)

The returned value contains:

<section class="wrapper">
    blah blah blah
    <div>
        blah blah
    </div>
    <section class="content">
        It's the one that I want
        <div>
            Whoa whoa whoa yeah!
        </div>
    </section>
    blah blah
</section>

I just want content but inclusive of its <section>.


Solution

  • Use DOMParser.

    var parser = new DOMParser();
    var doc = parser.parseFromString(aVariable, "text/html");
    var elm = doc.querySelector(".content");