[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2104
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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