Home > database >  jQuery how to create separate arrays for element inside repeated element
jQuery how to create separate arrays for element inside repeated element

Time:12-01

I have a bunch of container elements with the class .content-cont and inside each of these are some p tags. Id like to make a separate array for each container so if there are three containers, each one would create an array of p tags.

The reason being I want to find the middle p tag and give it a new class (which I can do). It's just the first part Im struggling with because it just makes one big array of all the p tags in all the containers.

my code is below...

    var arr = $( ".content-cont p" ).toArray();
    console.log(arr)

I hope that makes sense!


    $('.content-cont').each((i, el) => {
      let img = $('.content-cont .media-cont');    
      let $p = $(el).find('p');
      let mid = Math.floor($p.length / 2);
      let middle = $p.eq(mid);
      
      middle.addClass('middle');
      
      middle.before(img);
    });

CodePudding user response:

You can determine the middle element using the jQuery object without needing to create an array from it. If you get the length of the p elements within each .content-cont you can then use eq() to select the middle one.

Note that obviously the below logic works effectively when there's an odd number of p elements. I'll leave it to the reader to implement their own behaviour when there's an even number of elements.

$('.content-cont').each((i, el) => {
  let $p = $(el).find('p');
  let mid = Math.floor($p.length / 2);
  $p.eq(mid).addClass('middle');
});
.content-cont {
  border: 1px solid #CCC;
}
p {
  margin: 0;
}
.middle {
  font-weight: bold;
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="content-cont">
  <p>1</p>
</div>
<div class="content-cont">
  <p>1</p>
  <p>2</p>
  <p>3</p>
</div>
<div class="content-cont">
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>4</p>
  <p>5</p>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related