Arthur Tarasov Arthur Tarasov - 1 year ago 95
Javascript Question

How to use StartsWith selector on a variable?

According to jQuery's API

selector is intended to be used on the entire document.

For example,

var $elements = $( "span[id^='MJXc']" );

will find all
s in the DOM that have IDs starting with 'MJXc'.

But what if I have an array of elements stored in a variable and I want to select only those elements that start with ... out of that array? Can I still use the

The following doesn't seem to work and gives out
Uncaught SyntaxError: Unexpected token (

var $elements = $arrayofelements.( "span[id^='MJXc']" );

I did not add or remove any brackets, I just stuck a variable in front of the selector.

looks like this in console:


Ideally, I would like to get elements 0, 1, and 3 reuturned, skipping element 2 as it doesn't have ID starting with 'MJXc'.

Answer Source

Use the .filter() method in JQuery.


Like most JQuery methods, it takes a selector. It returns a new JQuery object containing only the elements that matched the selector (in this case, a span with an ID starting with MJXc).

// get only the spans inside #parent div
$spansToFilter = $('#parent').children();
$filteredSpans = $spansToFilter.filter('[id^=MJXc]');

// prove we've filtered out the span with no matching ID
$filteredSpans.each(function(i, item) {
<script src=""></script>

<span id="MJXc-Node-7.mjx-mrow">(external skip)</span>

<div id="parent">
    <span id="MJXc-Node-7.mjx-mrow">A</span>
    <span id="MJXc-Node-28.mjx-mi">B</span>
    <span class=".mjx-base">(skip C)</span>
    <span id="MJXc-Node-34.mjx-mi">D</span>

What you tried didn't work because in Javascript whatever.() would be invalid; You'd be trying to call a function with no name. In JQuery and javascript, you are always calling methods on the previous object in the chain obj.method(). Those methods are returning new JQuery objects which have the same set of methods, which is what allows the chaining to be possible. All the methods JQuery objects have are listed in the JQuery documentation, including .filter(), .find(), .children(), etc.