Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting ID + any number in jquery

I'm new to stackoverflow and jQuery altogether, so I'm having a little trouble making a simple function.

I basically have in my website a random number of links with id "filtro" + "some number", and I want to write only one code to the action of clicking in any of them (that would later impact on the class with same "filtro" + "some number").

Eg.: Click "#filtro3", do something on ".filtro3".

The problem is, I don't know how to write the string in jQuery for "any number". I'm thinking about doing something like this:

$(function () {
    $("#" + "filtro" + SOME NUMBER).click(function () {
            //Do something with the element "." + "filtro" + SOME NUMBER
    });
});

Any ideas? Thank you!!

Ps.: This is my first question, and I apologize if I made any mistakes.


SOLVED. dystroy's solution worked like a charm.

For future reference to others, I was making this code to make a simple filter menu for a picture gallery. This way I could hide/show pictures of certain topics.

like image 431
Fernanda Nia Ferreira Avatar asked Aug 08 '13 15:08

Fernanda Nia Ferreira


People also ask

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do you select all elements with an ID?

The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Can I select multiple ID in jQuery?

Given an HTML document and the task is to select the elements with different ID's at the same time using JQuery. Approach: Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element.

Can we add ID using jQuery?

Try this: $('element'). attr('id', 'value');


1 Answers

You seem to want

$(function () {
    $("[id^=filtro]").click(function () {
        var num = this.id.slice(6);
        // if there is a risk of ambiguity, you might check here that +num==num
        var $elem = $('.filtro'+num);
        ...
    });
});

Explanations :

  • $("[id^=filtro]") uses the starts with selector to select all elements whose id starts with "filtro"
  • this.id.slice(6); takes the part of the id starting after the sixth character. Maybe it would be clearer as this.id.slice('filtro'.length) or this.id.substring('filtro'.length)
like image 178
Denys Séguret Avatar answered Sep 21 '22 08:09

Denys Séguret