n00b0101
n00b0101

Reputation: 6893

how to remove parent element if it exists?

So, sometimes, my output will look like this:

<p><img src="someimage.jpg" /></p>
<p>A new paragraph</p>

Other times, it will look like this:

<img src="someimage.jpg />
<p>A new paragraph</p>

I'm trying to write some sort of "if" statement where, if the first p element in the markup surrounds an image tag, it will pull:

$j("p:eq(1)")

Otherwise, it will pull:

$j("p:eq(0)")

Alternatively, I could find all the img tags and if it's surrounded by

tags, remove those, but I'm not sure which one is better, or how to do either...

I tried the following, but it doesn't work:

if($j("img:eq(0)").parent().get(0).tagName == "p") {
      var pt = $j("p:eq(1)");
} else {
      var pt = $j("p:eq(0)");
}

Upvotes: 1

Views: 1006

Answers (3)

F&#225;bio ZC
F&#225;bio ZC

Reputation: 828

$('img').unwrap('p');

if you wish to remove the first parent element, just use .unwrap();

PS: note if u ara using jQuery in compability mode and if you need, change $ to $j

Upvotes: 0

Michael Haren
Michael Haren

Reputation: 108276

Try this:

var paragraphsWithoutImages = $('p').not(':has(img)')

(Live example)

Upvotes: 1

cletus
cletus

Reputation: 625087

This will grab the paragraph not containing an image, which fits your limited sample:

var pt = $("p:not(:has(img))");

It's probably the case that your actual markup will be more complex than this but there are many variations on this that you could do.

Upvotes: 1

Related Questions