Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector with specific attribute

Tags:

jquery

anchor

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?

like image 491
David Avatar asked Jun 04 '12 13:06

David


People also ask

What jQuery syntax selects HTML elements by a specific attribute and its value?

jQuery [attribute|=value] Selector The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us").

How do you select an element based on attributes and values?

CSS [attribute|="value"] Selector The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).

How get value of data attribute in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API.


2 Answers

$('a[rel="lightbox"]').click(
   function() {
       $("#change_flash").css("display", "block"); $("#my_flash").css("display", "none");
  });
like image 62
ilyes kooli Avatar answered Nov 15 '22 15:11

ilyes kooli


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:

  • attribute-equals selector.
  • atrribute-begins-with selector.
  • attribute-ends-with selector.
  • attribute-contains selector.
like image 5
David Thomas Avatar answered Nov 15 '22 17:11

David Thomas