Focusing on the initial element following CSS prioritization

Check out this codepen link: http://codepen.io/muji/pen/XpEYzO

I am looking to target the first element after it has been sorted using a CSS "order" property and apply another CSS property to it.

Is there a way to use jQuery or any other method to identify the first element after sorting, and then add a class or make changes to it? Thank you for your assistance.

.wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.featured {
  order: 1;
}
.normal {
  order: 2;
}
.wrap div {
  flex-basis: 50%;
  background: #ddd;
  border: 2px solid #000;
}

/*this is the part I need help with, as it should only apply to the first element AFTER applying the "order" attribute*/
.wrap div:first-of-type {
  flex-basis: 100%;
  background: #f00;
}
<h3>wp_query 1 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
</div>

<h3>wp_query 2 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
</div>

Answer ā„–1

There doesn't seem to be a specific CSS selector for selecting the "first in order" element, which would be quite useful as the order property is becoming more popular. Therefore, a script-based solution may be necessary.

If rearranging the elements works for your needs, that can easily be done. Here's a simple example:

// Function to determine priority of an element (lower number = higher priority)
function getPriority($el) {
  return $el.hasClass("featured") ? 0 : $el.hasClass("normal") ? 1 : 2;
}
// For each .wrap container...
$(".wrap").each(function() {
  var $this = $(this);
  
  // Get an array of its child elements
  var a = $this.children().get();
  
  // Sort the array based on priority
  a.sort(function(a, b) {
    return getPriority($(a)) - getPriority($(b));
  });
  
  // Append the sorted elements back to the parent
  $this.append(a);
});
.wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.wrap div {
  flex-basis: 50%;
  background: #ddd;
  border: 2px solid #000;
}

/* Style the first div differently */
.wrap div:first-of-type {
  flex-basis: 100%;
  background: #f00;
}
<h3>wp_query 1 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
</div>

<h3>wp_query 2 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer ā„–2

To achieve the desired effect, you can utilize jQuery to sort inner divs based on their position and then apply styling to the first one.

$('.wrap').each(function() {
  var sort = $(this).find('div').sort(function(a, b) {
    return $(a).position().top - $(b).position().top
  })
  $(sort[0]).addClass('first')
})
.wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.featured {
  order: 1;
}
.normal {
  order: 2;
}
.wrap div {
  flex-basis: 50%;
  background: #ddd;
  border: 2px solid #000;
}
div.first {
  flex-basis: 100%;
  background: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>wp_query 1 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
</div>

<h3>wp_query 2 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
</div>

Answer ā„–3

A different approach from the top position suggested by @Nenad Vracar would be to filter the elements with the lowest order in each group and emphasize the first one (based on dom order)

$('.wrap').each(function() {
  var items = $(this).children(),
    minOrder = Infinity,
    details = items.map(function(i, el) {
      var order = +$(el).css('order');
      if (minOrder > order) minOrder = order;
      return {
        element: el,
        order: order
      };
    }).get(),
    firstElement = details.filter(function(item) {
      return item.order == minOrder;
    })[0];
  
  $(firstElement.element)
    .addClass('highlight')
    .siblings()
    .removeClass('highlight');
  
});
.wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.featured {
  order: 1;
}
.normal {
  order: 2;
}
.wrap div {
  flex-basis: 50%;
  background: #ddd;
  border: 2px solid #000;
}
/*this is the part I need help with, as it should only apply to the first element AFTER applying the "order" attribute*/

.wrap .highlight {
  flex-basis: 100%;
  background: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3>wp_query 1 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
  <div class="featured">A featured item</div>
  <div class="normal">Normal</div>
</div>

<h3>wp_query 2 output:</h3>
<div class="wrap">
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>
  <div class="normal">Normal</div>;
</div>


If you were to modify the order based on media queries, you would need to implement this code on resize.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically populating fields in Laravel 8 after selecting a value from a dropdown menu

Having an issue once again.. If I choose the Banjarmasin-Jakarta route, the shipping cost field will be filled with 1.750.000 However, if I want to select "search shipping route" again, the shipping cost field will be filled with 0 Select "search shippi ...

The error message that appeared states: "TypeError Object[object object] does not have the SubSelf method, TypeError Object[object object] does not

As I delved into a WebGL project, leveraging the powerful Sim.js and Three.js libraries, an unexpected obstacle emerged: At a certain point, within the code, the constructor for THREE.Ray is utilized in this manner: var ray = new THREE.Ray( this.camera.p ...

Extract data from axios and display it in a Vue template

Having trouble displaying a value inside a div tag in my nuxt app. An error message keeps popping up saying "Cannot read property 'free_funds' of undefined. Still getting the hang of Axios and Nuxt. Could it be that Bootstrap requires JQuery to ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Retrieve data using AJAX and dynamically show it on an element using CodeIgniter

Just to clarify, I am brand new to AJAX and CodeIgniter. I came across this article which seems helpful for beginners like me: My goal is to update an Input Field in a form whenever the select html element changes. <select class="select" name="formul ...

Discover the process of utilizing doc.getElementbyClassName to determine if any of its elements are blank

On my HTML invoice table, I sometimes have empty elements that cause the row to misalign. To fix this, I want to add whitespace if an element is empty. Here is the structure of the table: <div class="invoiceTable"> <div class="titles2" style=" ...

Having trouble with CSS webkit radial not working on iPad's Safari Mobile browser?

I'm feeling confused right now. I have this gradient code background-image: -webkit-radial-gradient(50% 65%, ellipse cover, #f2f2f4, #201935 55%); It's working on Safari when I change the User Agent to Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3 ...

Struggling to Add angular-websocket to a MeanJS v0.4.1 Application: Dealing with an 'Unknown Provider' Error

I'm encountering some challenges while using angular-websocket in a controller within my MeanJS project. The version of MeanJS Iā€™m working with is v0.4.1. To begin, I installed it by running: bower install angular-websocket --save This creat ...

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

Requirements for adding information to a database table

I'm new to JavaScript and facing an issue that I need help with. I am trying to insert data into a database table based on certain conditions in my code, but even though I receive an error message when I input incorrect values, the data still gets ins ...

"The issue of the search form CSS class loading twice and causing placement issues following the completion of the AJAX

I implemented a search form that fetches data from the server and displays it in a div, which is working smoothly. However, when I added an ajaxComplete function to add a class for animating the results, it resulted in unexpected behavior. Upon entering t ...

Reorganize array of objects in JavaScript

So I am working with an array of objects structured like this: const data= [ { id: '6397f6f46b18bc89cb37053c', cost_center: null, plant: null, material: null }, { id: '6397f7166b18bc89cb372ff7', cost_center: &apo ...

The console displays "undefined" when formatting API data

I am attempting to format the data retrieved from an API since there is a lot of unnecessary information. However, when I try to display the formatted data in the console, it always shows as "undefined" or "null." I am importing and calling the fetch API ...

Guide to utilizing jQuery for setting values in all subsequent rows of a table

I have a table with 15 rows of text boxes labeled as text1, text2, and so on up to text15. If I enter text into, let's say, the 5th textbox, I want that same text to be automatically copied into all subsequent textboxes from the 6th through the 15th. ...

Making an API request using jQuery

I am currently working on creating a .js file that will send data to an external API, wait for a response, and then interpret the results. The external API I am using is XML-based and requires an HTTPS Post request with the XML content in the body (content ...

The CSS content spills beyond the edge of the screen

I am facing an issue with aligning my content in the center as it is currently shifting to the right side and going off the screen. Below is the code snippet I am working with: <?php /* Template Name: About Us */ $aboutheading = get_field('abou ...

The issue of the Dropdown Menu Not Remaining Fixed While Scrolling

There is a challenge with a Datetime Picker Dropdown Menu not staying in place when the user scrolls. Previous attempts to use .daterangepicker {position: fixed !important;} have been unsuccessful, causing the Datetime Picker to not stay fixed in its posit ...

The HTML button fails to respond when clicked

My website development process has hit a snag with the header buttons not functioning properly. I suspect the issues lie within lines 12 to 15 of the code snippet below: <!DOCTYPE html> <html> <head> <script src="https: ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Proper alignment of content in HTML using Bootstrap following the integration of .json data

After aligning the emergency hotlines properly, I am struggling to position the text under the image to display the data in three rows. I attempted col-4 but encountered issues with JSON. My objective is to show the image followed by the numbers directly b ...