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.

2
  • You have the above code as your HTML and you want to grab them using jQuery. Right? Commented Jul 2, 2018 at 18:56
  • document.querySelectorAll('.b') Commented Jul 2, 2018 at 18:56

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.