Search code examples
jqueryeachprepend

jQuery run function for identical elements?


I have a dozen identical elements whose contents need to be rearranged. I'm sure this is an easy question for jQuery masters, but I'm a total novice and this one has me stumped.

<li class="label">
   <div class="title">Card Title</div>
   <div class="content">
      <div class="header"></div>
      <img src="...">
   </div>
</li>

Which should look like:

<li class="label">
   <div class="content">
      <div class="header">
         <div class="title">Card Title</div>
      </div>
      <img src="...">
   </div>
</li>

I've tried to move via .prependTo(), but that duplicates every title into each label. I was hoping for a function that would say, "for this li.label, move its div.title into div.header", but I can't figure out the proper syntax. I've tried:

$("div.title").prependTo(".header"); (moves every title into each card)

$($("div.content")[0]).closest("div").prev().prependTo($(".header")[0]); (does the job, but only for the 1st card)

$("li.label").each(function() 
   {$("div.title").prependTo("div.header")
});

(just an embarrassing mess)

A couple things to note:

  • I have other lists with labels on the page that I do not want this to happen to, so if I could include a filter of :contains(card) (or whatever it would be), that would be amazing!
  • I am working front-front end; I can only use small scripts to change HTML and style content.

I think I've just mangled this poor language to death, and I'm terribly sorry if the answer is something I should know by now, but any help would be greatly appreciated. Thanks!


Solution

  • $("li.label").each(function(index) {
      if ($(this).find(".title:contains('Card')").length > 0) {
    /// cheak if title contans Card
        let title = $(this).find(".title");
        $(this).find(".title").remove();
    /// save that elements and then remove it
        $(this).find(".header").append(title);
    /// append back title to header
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <li class="label">
      <div class="title">Card Title</div>
      <div class="content">
        <div class="header">header</div>
        <img src="...">
      </div>
    </li>
    
    <li class="label">
      <div class="title">NOT</div>
      <div class="content">
        <div class="header">header</div>
        <img src="...">
      </div>
    </li>
    
    <li class="label">
      <div class="title">Card Title</div>
      <div class="content">
        <div class="header">header</div>
        <img src="...">
      </div>
    </li>