Jquery find all ids starting with a string?

79,844

Use the attribute-starts-with selector:

$('[id^="content_"]').hide();

To limit the search to elements within extra_content:

$('#extra_content [id^="content_"]').hide();
Share:
79,844

Related videos on Youtube

baggins
Author by

baggins

Updated on April 07, 2020

Comments

  • baggins
    baggins about 4 years

    Just wondered how I would search for all the ids starting with "content_" in the whole page and also a way to only find them in a named div called "extra_content". Once i have all the ids i want to hide them.

    Below is an example of what i want to find.

    <div id="content_1"></div> <-- Find
    <div id="content_2"></div> <-- Find
    <div id="contet_3"></div>
    
    <div id="extra_content"> 
        <div id="content_extra_1"></div> <-- Find
        <div id="content_extra_2"></div> < -- Find
    </div>
    

    Examples would be helpful.

    Thanks

    • Anand Thangappan
      Anand Thangappan about 13 years
      do you want to hide all or get the ids?
  • jbatista
    jbatista about 9 years
    I didn't know the attribute-starts-with selector (+1 for that to both of you) but I think you should add an attribute class to manipulate that instead of using the id attribute. It's more easy to understand, more clean and it helps to prevent bugs...
  • Mazhar MIK
    Mazhar MIK about 5 years
    Hi, I have a confusion, I have a scenario like this : <div id="min1"></div> <div id="max1"></div> <div id="min2"></div> ` <div id="max2"></div> ` . I am using this : $("[id^=min]", "[id^=max]").val('hello') to do something with them. It doesn't work. What is the problem ?
  • Danny Mahoney
    Danny Mahoney over 4 years
    @MazharMIK The problem you have is in your separating the selectors. It should be: $("[id^=min],[id^=max]").val('hello') . in this case. (P.S Classes are your friend)