.parents( [selector] )
<html> <head> <title>ThaiCreate.Com jQuery Tutorials</title> <style> b, span, p, html body { padding: .5em; border: 1px solid; } b { color:blue; } strong { color:red; } </style> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript"> $(document).ready(function(){ var parentEls = $("b").parents() .map(function () { return this.tagName; }) .get().join(", "); $("b").append("<strong>" + parentEls + "</strong>"); }); </script> </head> <body> <div> <p> <span> <b>My parents are: </b> </span> </p> </div> </body> </html>
<html> <head> <title>ThaiCreate.Com jQuery Tutorials</title> <style> p, div, span {margin:2px; padding:1px; } div { border:2px white solid; } span { cursor:pointer; font-size:12px; } .selected { color:blue; } b { color:red; display:block; font-size:14px; } </style> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript"> $(document).ready(function(){ function showParents() { $("div").css("border-color", "white"); var len = $("span.selected") .parents("div") .css("border", "2px red solid") .length; $("b").text("Unique div parents: " + len); } $("span").click(function () { $(this).toggleClass("selected"); showParents(); }); }); </script> </head> <body> <p> <div> <div><span>Hello</span></div> <span>Hello Again</span> </div> <div> <span>And Hello Again</span> </div> </p> <b>Click Hellos to toggle their parents.</b> </body> </html>
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท