Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all elements on a page whose element ID contains a certain text using jQuery

I'm trying to find all elements on a page whose element ID contains a certain text. I'll then need to filter the found elements based on whether they are hidden or not. Any help is greatly appreciated.

like image 250
user48408 Avatar asked Jul 30 '09 13:07

user48408


4 Answers

$('*[id*=mytext]:visible').each(function() {
    $(this).doStuff();
});

Note the asterisk '*' at the beginning of the selector matches all elements.

See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

like image 125
karim79 Avatar answered Oct 12 '22 12:10

karim79


If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });
like image 44
dnxit Avatar answered Oct 12 '22 12:10

dnxit


This selects all DIVs with an ID containing 'foo' and that are visible

$("div:visible[id*='foo']");
like image 22
port-zero Avatar answered Oct 12 '22 14:10

port-zero


Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});
like image 34
user48408 Avatar answered Oct 12 '22 12:10

user48408