ciar4n ciar4n - 7 months ago 30
Javascript Question

Move class name from child to parent

Looking to move the class name of an image to it's containing figure element using jQuery...

<figure class="wp-caption">
<img class="imghvr-hinge-up" src="image.jpg">
<figcaption >A sample caption</figcaption>
</figure>


In particular I would like to move any img tag class name beginning with 'imghvr-' to it's containing figure, if that containing figure has the class name 'wp-caption'. The result would look like the following...

<figure class="wp-caption imghvr-hinge-up">
<img class="" src="image.jpg">
<figcaption >A sample caption</figcaption>
</figure>


Hope that makes sense!) Any help would be greatly appreciated!

Answer

You could do it like this

$('img[class^="imghvr-"]').each(function() {
  var cl = $(this).attr('class');
  $(this).removeClass().parent('[class="wp-caption"]').addClass(cl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure class="wp-caption">
  <img class="imghvr-hinge-up" src="image.jpg">
  <figcaption>A sample caption</figcaption>
</figure>