Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select with partial name

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,

like image 764
Kris-I Avatar asked Oct 24 '11 09:10

Kris-I


People also ask

How to use id selector in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


3 Answers

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'));
});
like image 130
gion_13 Avatar answered Nov 12 '22 22:11

gion_13


Use starts with selector:

$('[name^="MyElement"]').length
like image 42
Sarfraz Avatar answered Nov 12 '22 20:11

Sarfraz


better using

$('input[name$="name"]')
like image 27
Romer Avatar answered Nov 12 '22 20:11

Romer