简体   繁体   中英

JQuery last selectors not working as expected

I have this big prob. In my code there are elements with the same ids(I know it is bad practice) so what I'm trying to do is to select the last, using jquery, element to apply some css. Following the logic this should be working. Below is the code

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#i:last").css("background-color", "yellow"); }); </script> </head> <body> <p id = "i">This is the first paragraph.</p> <p id = "i">This is the second paragraph.</p> <p id = "i">This is the last paragraph.</p> </body> </html> 

I always end up with the fist element ? Is it possible to do that? someone help please.

IDs are intended to be unique in an html document. I haven't looked into why this particular case isn't working with jQuery, but I'd have written the framework the same way. If there can be only one instance of an id, then there's no reason to implement pseudo selectors like 'first' or 'last'.

If you change the selection to be class-based, it works. I suggest you stop using multiple instances of the same id.

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(".i:last").css("background-color", "yellow"); }); </script> </head> <body> <p class="i">This is the first paragraph.</p> <p class="i">This is the second paragraph.</p> <p class="i">This is the last paragraph.</p> </body> </html> 

Selector using jQuery with id will always fecth you the first instance that is found.

You can instead get all the elements with native querySelectorAll and then use the :last psuedoElement selector.

We can get this working but is not a recommended approach . Use class instead where you think you will need to have multiple elements with the same id .

 var domElements = document.querySelectorAll('#i'); var jQueryElements = $.makeArray(domElements); var lastWithId = $(jQueryElements).filter(':last'); lastWithId.addClass('found'); 
 .found { border: 1px solid red; padding: 1em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id = "i">This is the first paragraph.</p> <p id = "i">This is the second paragraph.</p> <p id = "i">This is the last paragraph.</p> 

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