Pikk
Pikk

Reputation: 2743

jQuery or JS - how to wrap an image if the parent is not <a>?

I am struggling to get it to work. I need to wrap images that are not "clickable" inside a div.

The images that are children of a should not be wrapped.

I did the following:

if ($(window).width() > 960) {
  if (!$("img").parent().is("a")) {
    $("img").wrap('<div class="clickable_image"></div>');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>
  <img class="alignnone wp-image-60001 size-full" src="http://placekitten.com/g/200/300" alt="yyyyy" width="1400" height="1686">
</p>

<p>
  <a href="https://google.com" target="_blank">
    <img class="alignnone wp-image-60003 size-full" src="http://placekitten.com/g/500/300" alt="xxxx" width="1500" height="350">
  </a>
</p>

However I am making some mistakes, because it's not wrapping any image. And if I remove the !, it wraps both images. Only the image that is NOT inside a should be wrapped. How do I achieve that?

Upvotes: 2

Views: 56

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

You can use the descendent selector to wrap only the img elements which are children of p:

if ($(window).width() > 960) {
  $('p > img').wrap('<div class="clickable_image" />');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <img class="alignnone wp-image-60001 size-full" src="http://placekitten.com/g/200/300" alt="yyyyy" width="1400" height="1686">
</p>
<p>
  <a href="https://google.com" target="_blank">
    <img class="alignnone wp-image-60003 size-full" src="http://placekitten.com/g/500/300" alt="xxxx" width="1500" height="350">
  </a>
</p>

Upvotes: 2

Related Questions