简体   繁体   中英

Select newest/oldest element

I've seen it being suggested to use .last() to select the element from the selection that was made last, but said element could be inserted before the others of its kind, as shown on the snippet. Is there a way to select the newest or the oldest element in a given selection without using a global variable?

 popupWindow = $( '<div class="popup">' + ( '<button class="close">Close</button>' + '<div class="work-area"></div>' ) + '</div>' ); mainArea = $('.work-area'); $('#show-back').on('click', function() { popupWindow.clone().insertBefore(mainArea); drawOnFirst(); }); $('#show-front').on('click', function() { popupWindow.clone().insertAfter(mainArea); drawOnFirst(); }); $('body').on('click', '.close', function() { $(this).parent().remove(); }); function drawOnFirst() { $('.work-area').text('').first().text('I\\'m first!'); } 
 .popup { position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: rgba(255, 255, 255, 0.25); z-index: 99; } .work-area { width: 200px; height: 70px; background-color: #fff; border: 1px solid #080; position: absolute; top: calc(50% - 35px); left: calc(50% - 100px); } .popup .work-area { top: calc(50% - 15px); left: calc(50% - 80px); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="work-area"></div> <button id="show-back">Popup Before</button> <button id="show-front">Popup After</button> 

As far as I know, there is not a way to get the element that was added last.

You either need to use a variable to hold a reference to the "latest" modal window or when creating a new modal, you could create it a additional attribute which could be a timestamp for example. That way, you will be able to figure out which was added last.

Example:

popupWindow = $(
    '<div class="popup" data-created="' + (+new Date) + '">'+(
        '<button class="close">Close</button>'+
        '<div class="work-area"></div>'
    )+'</div>'
);

Then, you can easily sort all popups by their timestamp and get the newest one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM