Reputation: 5283
my main file is
<div id="man">
//some content
<div id="one">
//some content
<div id="two">
//some content
<div id="three">
//some content
<div id="four">
<a title="to delete">delete</a>
<a title="to reset">reset</a>
<a title="to change">change</a>
</div>...// all div ends...
<div id="woman">
//some content
<div id="one">
//some content
<div id="two">
//some content
<div id="three">
//some content
<div id="four">
<a title="to delete">delete</a>
<a title="to reset">reset</a>
<a title="to change">change</a>
</div>...// all div ends...
and the jquery is -
$("document").ready(function(){
$("a:contains(delete)").click(function(){
alert($(this).parent().parent().parent().parent().parent().attr("id"))
})
})
is there any another way to find the top parent instead of using this...??
Upvotes: 0
Views: 93
Reputation: 18233
Well if you must stick rigidly to that html structure (can't add classes, etc.) then you can certainly make use of the structure in your selector;
$(document).ready(function(){
$("a:contains(delete)").click(function(){
var pId = $(this).parents("#man").attr("id") ||
$(this).parents("#woman").attr("id");
alert(pId);
});
});
This is also assuming that your html is well-formed (i.e that your divs for man are all closed).
Since IDs are unique (or should be, though not all of yours are...) and the "man" and "woman" elements must be disjoint, an element can only ever be the child of one or the other -- and since this selector would be bound to a link in one of the two, you know that if its parent isn't a "man" it must be a "woman".
Upvotes: 1
Reputation: 150080
If you can modify your html slightly and give those top-level divs a common class:
<div id="man" class="top">
...
<div id="woman" class="top">
...then you can use the .closest()
method to select them:
$("a:contains(delete)").click(function(){
alert($(this).closest('div.top').attr("id"))
})
Note that your current html markup is invalid because you are not supposed to give the same id
to more than one element. (So given that you should change your markup to fix that it will be no problem to also add a class to the top-level divs.)
EDIT: Demonstration that the above works even when "man" and "woman" aren't at the top level: http://jsfiddle.net/NVQXq/
Upvotes: 2