Regular expression or javascript to isolate a div with a specific class and it's closing </div>

Viewed 34

I'm trying to find a regex that will match HTML that is in a string starting with <div class="table-responsive" with it's closing </div> tag, ignoring the closing divs that don't close the div with the class "table-responsive". I downloaded HTML from another page on a website with Javascript and I'm setting the innerHTML of a div to contain the info I want displayed from the downloaded HTML. The problem is that I only want the tag starting with <div class="table-responsive" and the closing div displayed and I'm trying to cut out everything but I don't know what the best method is to do that. Can anyone make a suggestion how I can do that?

1 Answers

It is possible to use regex, first by adding nesting level info to divs, extracting the relevant range based on nesting level, and removing the nesting level info.

It is much easier to convert the HTML to an in-memory DOM, and extract the relevant data. Here is an approach using jQuery:

const html = '<div class="top"> <div class="table-responsive"> <div class="inner1"> <div class="inner2">blah</div> </div> </div> </div>';
let extractedHtml = $(html).find('.table-responsive').prop('outerHTML');
console.log(extractedHtml);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Output:

<div class="table-responsive"> <div class="inner1"> <div class="inner2">blah</div> </div> </div>

If you only want the HTML inside the div tag use this:

let extractedHtml = $(html).find('.table-responsive').html();
Related