0

I'm trying to create an array of element attribute values where the attribute name ends with the string "toselect". I have lots of these elements on the page but I only want the values for the element I clicked on. I don't know if jquery .attr() function takes any wild card characters. I'm using jquery but I will also be happy with a pure javascript anwser

I know this doesn't work but I need something similar.

var attrs[] = $(this).attr('*toselect');

The html looks like this

<div class="someclass" data-firsttoselect="somevalue1" data-secondtoselect="somevalue2" data-thirdtoselect="somevalue3"></div>

So the array 'attrs' should contain {somevalue1, somevalue2, somevalue3}

4
  • You should probably be using data-* attributes, and not your own made up invalid attributes ? Commented Mar 19, 2015 at 10:42
  • Just FYI, that HTML is invalid. You cannot add non-standard attributes to elements. Try using data-* attributes instead. Commented Mar 19, 2015 at 10:42
  • I'll do that but I still don't know how to select them Commented Mar 19, 2015 at 10:43
  • There's no built in way to select elements based on partial attribute names, you have to iterate and filter Commented Mar 19, 2015 at 10:48

1 Answer 1

0

Firstly, that HTML is invalid. You cannot add non-standard attributes to elements without making the page invalid, which may cause UI and JS issues. Try using data-* attributes instead:

<div class="someclass" data-firsttoselect="somevalue1" data-secondtoselect="somevalue2" data-thirdtoselect="somevalue3"></div>

From there you can create an array of the *toselect values by using map() and testing the value against a Regex, like this:

var data = $('.someclass').data();
var values = $.map(data, function(value, key) {
    if (/toselect$/i.test(key))
        return value;
});

Example fiddle

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

3 Comments

and yet Angular completely depends on non-standard attributes?
@Alnitak indeed. Most renderers are lenient and will let you away with it, but the HTML is still invalid. Here's a question on the subject: stackoverflow.com/questions/18665303/…
use of non standard attributes has been common for years , prior to data- attributes. Browsers won't crap out, just ignore

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.