views:

228

answers:

4

Hello,

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 = "";
 });
+2  A: 

take a look at the find function

http://docs.jquery.com/Traversing/find

within the each function you can find what you need like this:

$(this).find('h2').text();
$(this).find('img').attr('src');
Josh
+1  A: 

You're close.

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

Give that a shot.

ewakened
+3  A: 

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();
});
CalebD
A: 

I think you want this:

$("#services div.left").each(function () {
   var $this_html = $(this).html(); // don't know if you still want this
   var h2_text = $(this).find(">h2").text();
   var img_src = $(this).find(">img").attr("src");
 });
  • div.left is added so you always get a div with the correct elements.
  • We use > in the find function to grab the children (more efficient).
  • Remove the $this_html line if you don't need the entire HTML in addition to the h2/img, the latter stuff doesn't depend on it.
DisgruntledGoat