alt

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?

0


source to share


7 replies


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");
});

      

+2


source


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' );
});

      

+4


source


Wouldn't it be better to store the id in a link, then in your manual service, find the content of the div by id and execute your trigger? This way you are not tied to a specific hierarchy.

+2


source


Perhaps you can use xpath to go from A to DIV in one go?

Edit: Apparently there are no xpath selectors in jquery (thanks guy in the comments for pointing this out)

+1


source


Out of my head:

$("a.editcontent").click(function(){
    $(this).parents("h2").slice(0, 1).next(".content").trigger("edit");
});

      

+1


source


I agree with Sprintstart

var clickHandler = function (link) {
     $(link.data.action).trigger("edit");
}

$('a.editconent').bind('click', {action:'.content'}, clickHander);

      

Then you can be much more targeted at the jQuery statement that fires the edit event.

+1


source


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.

0


source







All Articles