0

So if I have a string of HTML, I was wondering how I would go about getting an array of parsed elements from that string that are of a certain class. For example, if I had a string that contained the following HTML:

<div>
    <div class="a">
        <div class="b">
        </div>
    </div>
    <div class="a">
        <div class="b">
        </div>
    </div>
    <div class="a">
        <div class="c">
        </div>
    </div>
</div>

How would I get an array of all of the elements with a class of "b"? I have tried looking for a solution but I cannot find anything that works when the elements you are looking for are nested a couple layers.

Russell C.
  • 588
  • 6
  • 25
  • You have the above code as your HTML and you want to grab them using jQuery. Right? – Saif Jul 02 '18 at 18:56
  • [document.querySelectorAll('.b')](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) – wiesion Jul 02 '18 at 18:56

3 Answers3

2

You can put html inside $() and it will convert it into elements, of which you can then filter/find off of.

var testStringOfHtml = `
<div>
    <div class="a">
        <div class="b">
        </div>
    </div>
    <div class="a">
        <div class="b">
        </div>
    </div>
    <div class="a">
        <div class="c">
        </div>
    </div>
</div>
`;

console.log($(testStringOfHtml).find('.b').get());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Taplar
  • 24,788
  • 4
  • 22
  • 35
2

var html = '<div><div class="a"><div class="b"></div> </div><div class="a"><div class="b"></div></div><div class="a"><div class="c"></div></div></div>';

var el = document.createElement( 'html' );
el.innerHTML = html;


var selectedB = el.querySelectorAll( '.b' ); 

console.log(selectedB)
Tareq
  • 5,283
  • 2
  • 15
  • 18
1

Sounds like you're looking for document.querySelectorAll. Here is the MDN documentation so you can familiarize yourself: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Here is an example of how to use it in your code:

//use querySelectorAll method
var bElements = document.querySelectorAll('.b');

//you can iterate over and see all the elements
for (var i = 0; i < bElements.length; i++) {
  console.log(bElements[i]);
}
<div>
  <div class="a">
    <div class="b">
    </div>
  </div>
  <div class="a">
    <div class="b">
    </div>
  </div>
  <div class="a">
    <div class="c">
    </div>
  </div>
</div>
Tom O.
  • 5,730
  • 2
  • 21
  • 35