[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2345
  • Last Modified:

jQuery: Closest parent with attribute defined

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

0
hankknight
Asked:
hankknight
  • 3
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
The first one in the body :
$("div[dir]", "body").attr("dir");

Open in new window

0
 
hankknightAuthor 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

0
 
leakim971PluritechnicianCommented:
Ok, check this : http://jsfiddle.net/x6d29/

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

Open in new window

0
 
hankknightAuthor 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.
0
 
leakim971PluritechnicianCommented:
 var $all_wit_a_dir_att = $("div[dir]");

Open in new window

0

Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now