views:

48

answers:

3

If I have this HTML:

<a id="test" referenceId="test23" href=''>Test</a>

and I want to get the selector based on the referenceId attribute (not the id)

I know I can do this

$('#test'). . ..

but I want to understand if I can do a similar thing but using the referenceId attribute to get the selector.

+3  A: 

$('[referenceId="test23"]')

Coronatus
+2  A: 

$('[attribute=someValue]'). . . .

Randall Kwiatkowski
+4  A: 

Searching from attribute values should not be done directly on the root document, and especially not using a very generic selector as it is quite slow, and should be limited to a specific parent, a specific tag name, or on elements with a shared CSS class. For example, in your case, if referenceId is an attribute only specified to anchor elements, you query :

$("a[referenceId='someValue']")...

If you have this attribute on different tag names, you can narrow the search specifying a common parent, or using multiple selectors, etc. in the same query. For example :

$("div#parent [referenceId='someValue']")... // use div#parent as base element
$("a[referenceId='someValue'], span[referenceId='someValue']")... // search A and SPAN tags only
$(".ref[referenceId='someValue']")... // search any element with "ref" CSS class
// etc.

Note that it is recommended to enclose the attribute value in quotes. You can read more about selectors from the jQuery API docs.

Yanick Rochon