Home > Software design >  jQuery appendTo effecting multiple elements
jQuery appendTo effecting multiple elements

Time:04-05

I'm using a simple appendTo to move some <figcaption> tags inside some <a href>. I can do this easy enough using:

$('.company-panel figcaption').appendTo('.company-panel a');

But I have multiple <div > on the page and it's moving all <figcaption> rather than the ones relative to the panel.

$('.company-panel figcaption').appendTo('.company-panel a');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div >
  <a href="#">link - move figcaption below here</a>
  <figcaption>Caption 1</figcaption>
</div>

<div >
  <a href="#">link - move figcaption below here</a>
  <figcaption>Caption 2</figcaption>
</div>

<div >
  <a href="#">link - move figcaption below here</a>
  <figcaption>Caption 3</figcaption>
</div>

This is what I want outputted:

<div >
  <a href="#">link <figcaption>Caption 1</figcaption></a>
</div>

<div >
  <a href="#">link <figcaption>Caption 2</figcaption></a>
</div>

<div >
  <a href="#">link <figcaption>Caption 3</figcaption></a>
</div>

CodePudding user response:

here is the code:

$('.company-panel').map((i,el)=>{
  let fig = $(el).children('figcaption').text();
  $(el).children('a').html(`<figcaption>${fig}</figcaption>`);
  $(el).children('figcaption').remove();
});

CodePudding user response:

jQuery has different traversing methodes for this one the .siblings() methode is the right

$('.company-panel figcaption').appendTo($(this).siblings('a'));
  • Related