views:

44

answers:

1

I want to find all the elements on my page that have a 'name' attribute containing 'x' or 'y' and add a certain class to those elements.

So, the logic I'm looking to apply is

If anything has 'x' or 'y' in the name attribute then add .yepItHasXorY

It seems like a simple thing. I understand how to search based on an ID or Class but not the name attribute...

+1  A: 

You can use an attribute-contains selector, like this:

$("[name*=x], [name*=y]").addClass('yepItHasXorY');

Though, I would add an element type, on there or maybe :input to you're only looking at elements you care about (otherwise it's a much more expensive selector).

Nick Craver
This is probably the only way but I could imagine that it is very inefficient as it has to traverse over all elements of a page...
Felix Kling
@Nick Per our prior discussion (http://tinyurl.com/23xnk4m) would this be an appropriate time for .find() ? :-)
Chris
@Felix - Yup, added some notes about this already :)
Nick Craver
@Chris - This is a `.find()`, a `$(document).find('[name*=x], [name*=y]')` :) Some other restrictions on the selector would be good though, element types, or descending from an ID for example.
Nick Craver
So I could create an array of elements to look through and name attributes to look for. Would that be less expensive? Say, something like var lookat= ['p', 'img', 'h1'] and lookfor=['x', 'y']; and the code would loop through it and then I could addClass from there? Or would that just triple the work?
Ofeargall