JQuery selector with specific attribute

I have this code:

$('a').click( function() { $("#change_flash").css("display", "block"); $("#my_flash").css("display", "none"); }); 

But this works for all anchor elements. I would like to influence this script only on anchor elements that contain the rel = "lightbox" attribute.

How can i achieve this?

+6
source share
2 answers
 $('a[rel="lightbox"]').click( function() { $("#change_flash").css("display", "block"); $("#my_flash").css("display", "none"); }); 
+4
source

Use the following:

 $('a[rel="lightbox"]').click( function(){ // do your stuff here }); 

The notation attribute="value" (see links).

There are other options:

  • an attribute begins with: attribute^="value" ,
  • attribute-ends-with: attribute$="value",
  • attribute-contains: `attribute * =" value ".

Please note that, of course, if $('[rel="lightbox"]') is an absolutely correct selector, this will force jQuery to check every element on the page for this attribute and value to bind / assign the click event c); therefore, it is always better to use a tag name, therefore $('a[rel="lightbox"]') or a class name to limit the number of elements that jQuery must perform to search in order to find the corresponding elements.

Although in modern browsers I seem to remember that this “search” is carried over to the native document.querySelectorAll() , and not to the use of Sizzle, but even in this case it is best to limit the amount of work that the browser needs to do.

Literature:

+5
source

Source: https://habr.com/ru/post/917371/


All Articles