David
David

Reputation: 1963

jQuery selector with specific attribute

I've got this code:

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

But this one works for all anchor elements. I would like to influence with this script only for anchors elements which contains rel="lightbox" attribute.

How can I achieve it?

Upvotes: 4

Views: 5471

Answers (2)

David Thomas
David Thomas

Reputation: 253328

Use the following:

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

This is using the attribute="value" notation (see references).

There are, also, other options:

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

Note, of course, that while $('[rel="lightbox"]') is an absolutely valid selector all by itself, this will cause jQuery to examine every element on the page for that attribute and value in order to bind/assign the click event(s); therefore it's always best to use a tag-name, hence the $('a[rel="lightbox"]'), or a class-name in order to limit the number of elements jQuery has to search through to find the matching elements.

Although in modern browsers I seem to remember this 'search' is handed over to the native document.querySelectorAll(), rather than using Sizzle, but even so it's best to limit the amount of work a browser need do.

References:

Upvotes: 5

ilyes kooli
ilyes kooli

Reputation: 12043

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

Upvotes: 5

Related Questions