ngreenwood6
ngreenwood6

Reputation: 8216

jQuery each() help

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.

Upvotes: 0

Views: 1425

Answers (6)

Ismael
Ismael

Reputation: 2330

p = $('#p img');
p.each( function(i, val) { 
    $(val.id).append("<strong>Hello</strong>");
});

Upvotes: 0

Nathan Kleyn
Nathan Kleyn

Reputation: 5143

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>');

Upvotes: 3

powtac
powtac

Reputation: 41040

$('p.desc img').before('<span>here comes an image</span>');

Upvotes: 1

Greg
Greg

Reputation: 321588

Something like this should do the trick:

$('p.descr img').before('<span>New Stuff</span>');

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

$('p').each(function()
{
    $(this).find('img').each(function()
    {
        // do stuff with the image
    });
});

Upvotes: 2

Boris Gu&#233;ry
Boris Gu&#233;ry

Reputation: 47585

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

Manual

Upvotes: 0

Related Questions