jQuery select with partial name

2019-06-15 11:35发布

问题:

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,

回答1:

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'));
});


回答2:

Use starts with selector:

$('[name^="MyElement"]').length


回答3:

better using

$('input[name$="name"]')


回答4:

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;