2

Is there a way to find all the child elements of a div that has id like:-

child_*_of_parent

HTML

<div id="parent">
  <div id=child_1_of_parent>...</div>
  <div id=child_2_of_parent>...</div>
  <div id=child_3_of_parent>...</div>
  <div id=some_other_id_1>...</div>
  <div id=some_other_id_2>...</div>
</div>

I want all children with ids:- child_1_of_parent, child_2_of_parent, child_3_of_parent

My Try

jQuery("#parent").find("div[id='child_*_of_parent']");
Abhi
  • 4,123
  • 6
  • 45
  • 77

3 Answers3

4

Try to check starts with and ends with

Try like this

$("div[id ^='child_'][id $='_of_parent']")
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
1
Try the following:

$("#parent div[id$=_of_parent][id^=child]")
Muhammad Atif
  • 1,050
  • 1
  • 9
  • 21
  • 2
    Can you add explanations to your code? For example `id$=` means string ends with, etc. It might helps others trying to understand your solution. – Mario Tacke Dec 23 '15 at 05:16
  • Those are pretty neat selectors: [jQuery Ends With](https://api.jquery.com/attribute-ends-with-selector/) and [jQuery Starts With](https://api.jquery.com/attribute-starts-with-selector/) – julian soro Dec 23 '15 at 05:23
1

In my knowledge it can be done be done in two ways

Matching pattern Here just matching the id pattern of the child elements.

$('#parent').children().each(function(){
   if( $(this).attr('id').match("_of_parent") ) {
        console.log($(this));
   }
});

Using Attribute Selector.Here checking the begining & ending pattern of the id ^ is used to check the begining of string & $ can be used to check the ending pattern

var a =($("div[id ^='child_'][id $='_of_parent']"))

WORKING MODEL

Hope this will be helpful

brk
  • 48,835
  • 10
  • 56
  • 78