Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery finding a specific H4 with no id nor name nor class

i have a simple question about JQuery...

I have a main <div> containing some divs, which have dynamical ids. each child div has a <h4> tag in it. These h4 does not have any id, nor class, nor name. They just have some text in it.

Here is what i'm talking about :

<div id="main_div">
   <div id ="div01">
      <h4>Sometext01</h4>
   </div>
   <div id ="div02">
      <h4>Sometext02</h4>
   </div>
   <div id ="div03">
      <h4>Special Text!!!</h4>
   </div>
   <div id ="div04">
      <h4>Sometext04</h4>
   </div>
</div>

I would like to get the parent div's id of the h4 which text is "Special text!!!" (so, here, in this example, it is div03).

But, unfortunately, these ids are auto generated (by Sugarcrm, for those who know), and i can't know by advance the id's name. So that is why i have to pass by the h4.

I know i can use the jQuery function below to pass through all h4

allMyH4.each()

And i know i can use the jQuery function below to find the parent of my desired h4

myFoundH4.parent()

But i'm getting some trouble on searching the h4 by their text() (or html() )

Could you please help me on that?

Thanks a lot

EDIT few hours later :

Thanks to @Bhushan , i could do what i really wanted. It just has a restriction : my user MUST not change h4 texts NOR giving several h4 the same name containing my string. For another solution, try @rory too, it did not work for me, but it had been tested by others, and it seems to be better than contains.

like image 640
Gaelle Avatar asked Feb 03 '26 05:02

Gaelle


1 Answers

You can use filter():

var $h4 = $('h4').filter(function() {
    return $(this).text() == 'Special Text!!!';
});
console.log($h4.parent().prop('id'));

This will ensure an exact match on the text property, not a partial match as the :contains selector will give. filter should also be faster.

like image 121
Rory McCrossan Avatar answered Feb 04 '26 19:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!