tags:

views:

59

answers:

6

I have this structure

<p class="descr">
  <span>something here</span>
  <img src="test" />
</p>

<p class="descr">
  <span>somthing else here</span>
  <img src="test2" />
  <img src="test3" />
</p>

so there can be more than one image inside of a <p> element.

What i need to do is loop through each <p> and then each <img> inside of it and add something to the front of it. Any help is appreciated. I tried doing an .each() but it's not working.

A: 
$('p img').each(
  function(k, v)
  {
    $($(v).parents()[0] + 'span').html('Your text here');
  }
);

Manual

Boris Guéry
+1  A: 
$('p').each(function()
{
    $(this).find('img').each(function()
    {
        // do stuff with the image
    });
});
Matt Ball
It would be advisable to combine the `each` statements to prevent unnecessary DOM traversal.
Nathan Kleyn
A: 

Something like this should do the trick:

$('p.descr img').before('<span>New Stuff</span>');
Greg
+1  A: 
$('p.desc img').before('<span>here comes an image</span>');
powtac
+3  A: 

Try this:

$('p.descr > img').each(function() {
    // Make this code do what you want.
    $(this).prepend('<span>Prepended Content</span>');
});

The variable this represents the current image inside this function. In this example, I'm injecting a span element before each image inside a paragraph, but only direct descendant images.

This function can be shortened if you're only going to add another element before each image:

$('p.descr > img').prepend('<span>Prepended Content</span>');
Nathan Kleyn
A: 

p = $('#p img');

p.each( function(i, val) {

$(val.id).append("Hello");

});

Ismael