19

I'd like the count the element on the page with the name :

  • MyElement_1
  • MyElement_2

Then I'd like get element MyElement

Thanks,

gion_13
  • 41,171
  • 10
  • 96
  • 108
TheBoubou
  • 19,487
  • 54
  • 148
  • 236

4 Answers4

33
var elements = $('[name^=MyElement]');
var length = elements.length;

If you want some more advanced filtering, you can filter all the dom nodes by matching your own rules :

var elements = $('[name]').filter(function(){
    return /^MyElement_\d+$/.test($(this).attr('name'));
});
gion_13
  • 41,171
  • 10
  • 96
  • 108
13

Use starts with selector:

$('[name^="MyElement"]').length
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

better using

$('input[name$="name"]')
Serjik
  • 10,543
  • 8
  • 61
  • 70
Romer
  • 21
  • 1
  • 1
    This will select `input` elements whose `name` attribute value **ends with** `name`, not what OP wants. – Tushar Oct 26 '16 at 03:03
0

To find an element by the name attribute, use:

$('[name=something]'); 

use *=, ^=, etc. to be more or less specific in the search term. Look at the jquery selectors page for more info on how to use them.

The exaple above returns all elements that match. Suffix this with .length and you'll get the number of elements that are found, like so:

 $('[name=something]').length;
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78