JQuery - Finding Better Selector Syntax
I have some HTML code that looks something like this:
<li id="someid-11">
<img src="..." alt="alt" />
<h2><a href="somelink"> sometext </a>
<span><a class="editcontent" href="?action=editme">Edit</a></span>
</h2>
<div id="11" class="content">
<!-- // content goes here -->
<div class="bottom_of_entry"> </div>
</li>
I am using a.editcontent to activate an in-place edit method on div.content. My current selector looks like this
jQuery('a.editcontent').bind('click', (function(){
jQuery(this).parent('span').parent('h2').next('.content').trigger('edit');
}
It works, but its ugly. There must be some better way to do this, right?
source to share
I have recommended Sprintstar's solution. but if you don't like it use this:
$("a.editcontent").click(function(){
$(this).parents("h2").next(".content").trigger("edit");
});
If you have one more "h2":
$("a.editcontent").click(function(){
$(this).parents("h2:first").next(".content").trigger("edit");
});
source to share
I think using some meta attributes would be the best solution.
<li id="someid-11">
<img src="..." alt="alt" />
<h2><a href="somelink"> sometext </a>
<span><a rel="11" class="editcontent" href="?action=editme">Edit</a></span>
</h2>
<div id="11" class="content">
<!-- // content goes here -->
<div class="bottom_of_entry"> </div>
</li>
(added link rel = "11" to link)
And then in JavaScript:
$( 'a.editcontent' ).click(function()
{
$( '#' + $(this).attr( 'rel' )).trigger( 'edit' );
});
source to share
I think it is difficult to read because you need to go from one element back to another. If you are referring to as a shared container, these paths will seem more meaningful.
var listitem11 = $("#someid-11");
listitem11.find('a.editcontent').bind('click'), (function(){
listitem11.find('.content').trigger('edit');
}
Now, I suspect you have multiple list items to deal with, in which case you need a closed loop that you didn't need before. However, I think it puts you ahead.
source to share