Search code examples
jqueryforeachhtml-content-extraction

Using jQuery to Grab Content


I'm trying to pull a couple variables from the following block of html. If you wouldn't mind helping, it would be greatly appreciated!

<div id="services">
    <div id="service1">
      <div class="left">
        <img alt="Service Picture" src="/images/service-picture.jpg" />
        <h2 class="serviceHeading">A Beautiful Header</h2>
        <p>Some nice text.</p>
      </div>
      <div class="right">
        <p>Some more nice text.</p>
      </div>
      <br class="spacer"/>
      <a class="topButton" href="#" title="Back to Top">Back to Top</a>
    </div>
    <div id="service2">
      <div class="left">
        <img alt="Service Picture" src="/images/service-picture-2.jpg" />
        <h2 class="serviceHeading">Another Beautiful Header</h2>
        <p>Some even nicer text.</p>
      </div>
      <div class="right">
        <p>Some even more nicer text.</p>
      </div>
      <br class="spacer"/>
      <a class="topButton" href="#" title="Back to Top">Back to Top</a>
    </div>
  </div>

I'd like the function to traverse through #services and get the src values for each img, as well as the content from each <h2>.

This is what I have so far...

 $("#services div").each(function () {
   var $this_html = $(this).html();
   var h2_text = "";
   var img_src = "";
 });

Solution

  • This should work. It is important to use the selector #services > div because each service div has a child div. Without the child selector you will get each service twice.

    $("#services > div").each(function () {
       var imgSrc= $(this).find('img').attr('src');
       var headerContent = $(this).find('h2').text();
    });