We help IT Professionals succeed at work.

jQuery: Closest parent with attribute defined

hankknight
hankknight asked
on
Using jQuery, how can I find the closest parent with the "dir" attribute defined?

<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
  alert('The closest parent with the attribute dir defined has the dir value of ????');
});
</script>

</head>
<body>

<div>
 <div>
  <div dir="ltr">
   <div>
    <div>
     <div>
      <div>
       <p id="xyz"></p>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

</body>
</html>

Open in new window

Comment
Watch Question

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
The first one in the body :
$("div[dir]", "body").attr("dir");

Open in new window

Author

Commented:
I want the closets parent, not the first one in the body.

In the example below, it should find "ltr" not "rtl".

<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
  alert('The closest parent with the attribute dir defined has the dir value of ' + $("div[dir]", "body").attr("dir") );
});
</script>

</head>
<body>

<div>
 <div dir="rtl">
  <div>
   <div dir="ltr">
    <div>
     <div>
      <div>
       <p id="xyz"></p>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

</body>
</html>

Open in new window

Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
Ok, check this : http://jsfiddle.net/x6d29/

$("#xyz").closest("div[dir]").attr("dir");

Open in new window

Author

Commented:
Thanks!  Is there a way to get it to test for all elements with the "dir" attribute?  I also want to look for these in <p> and <span> tags.
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
 var $all_wit_a_dir_att = $("div[dir]");

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.