Dexygen
Dexygen

Reputation: 12561

Find elements that end with a variable

In my searches I have found plenty of questions/answers on how to find elements that end with a specific string. I've done a quick search and have not found anything specific about how to find elements that end with a variable. I did find this question/answer about how to use Javascript variables in jQuery selectors in general but I cannot get it to work and I wonder if it's because I'm trying to work against a set of elements I've already filtered down to.

Here are some id's of the elements I've already filtered:

["ms-goal-select-0", "ms-goal-input-0", "ms-goal-select-1", "ms-goal-input-1", "ms-goal-select-2", "ms-goal-input-2"]

And here is the (beginning of) the for loop I'd like to use to find and work with the select and input elements:

for (var x=0;;x++) { //will break when element(s) not found
    selectEl = filteredElements.find('[id$="select-' + x + '"]');
    inputEl = filteredElements.find('[id$="input-' + x + '"]');
    ....

But the above does not find the elements starting from the first iteration when x==0. What am I doing wrong?

Upvotes: 2

Views: 95

Answers (2)

Dave
Dave

Reputation: 10924

jQuery's .find() only searches in descendants. I think you want to do a .filter() instead. I'd write this using the version of .filter() that takes a function and use a regular expression to match the elements you want:

var filteredElements = $("div");
var selectEl = filteredElements.filter(function() {
  return this.id.match(/.-select-\d*$/);
});
var inputEl = filteredElements.filter(function() {
  return this.id.match(/.-input-\d*$/);
});

console.log(selectEl.toArray());
console.log(inputEl.toArray());
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="ms-goal-select-0"></div>
<div id="ms-goal-input-0"></div>
<div id="ms-goal-select-1"></div>
<div id="ms-goal-input-1"></div>
<div id="ms-goal-select-2"></div>
<div id="ms-goal-input-2"></div>

Upvotes: 1

StriplingWarrior
StriplingWarrior

Reputation: 156524

Try using filter instead of find:

for (var x=0;;x++) { //will break when element(s) not found
    selectEl = filteredElements.filter('[id$="select-' + x + '"]');
    inputEl = filteredElements.filter('[id$="input-' + x + '"]');
    ....

Find only looks for matching children of the elements in filteredElements, whereas filter looks at the elements themselves.

Upvotes: 1

Related Questions