Home > other >  I need to find all elements with the same class name and address the first one
I need to find all elements with the same class name and address the first one

Time:02-02

I have a problem and I am not sure how to solve it or if it's even possible: in WordPress I have built a simple event calender. Now I want to style every first event of a certain date. How can I select this first event?

https://arneteubel.com/kunden/rz-test/termine/

This is the demo page. Every event gets it's date as a class so what I am looking for is something like:

  1. Find elements with the same class
  2. Select the first element and apply a style

I can not group my events by date…

Now is that even possible? Maybe with PHP or jQuery?

Thank you!

CodePudding user response:

I prefer to work with data- attribute instead of classes

data-date="feb34454" instead of

See the next example

$(document).ready(function(){
  $(".ct-nestable-shortcode").each(function(){
    let the_date = $(this).find("> div").data('date');
    $("[data-date='" the_date "']:first").css("background" , "yellow");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div data-date="feb34454">feb34454</div>
</div>
<div >
  <div data-date="feb34454">feb34454</div>
</div>
<div >
  <div data-date="feb34454">feb34454</div>
</div>

Note: Don't forget to include jquery

CodePudding user response:

You should use CSS for styles if at all possible.

Here's a CSS solution stolen from this answer:

 /* 
 * Select all .red children of .home, including the first one,
 * and give them a border.
 */
.home > .red {
    border: 1px solid red;
}

... then "undo" the styles for elements with the class that come after the first one, using the general sibling combinator ~ in an overriding rule:

/* 
 * Select all but the first .red child of .home,
 * and remove the border from the previous rule.
 */
.home > .red ~ .red {
    border: none;
}
  •  Tags:  
  • Related