2

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 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

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...
Per our prior discussion (tinyurl.com/23xnk4m ) would this be an appropriate time for .find() ? :-)
@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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.