6

jQuery - Not sure which method to use, the nearest () and parent () do not work

 2 years ago
source link: https://www.codesd.com/item/jquery-not-sure-which-method-to-use-the-nearest-and-parent-do-not-work.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

jQuery - Not sure which method to use, the nearest () and parent () do not work

advertisements

God i feel like i'm spamming stackoverflow, this is my 3rd post for today. Sorry, heh.

I even posted a question regarding this before, kind of, but i've changed the code a bit since so i thought it was better to post a new question.

$('.pmlist ul li h4 .toggle').click(function() {
    $(this).closest('.meddel').toggle(250);
});

That's what i've got now. The reason why the closest() method isn't working is because the div .meddel is just next to the h4 element. And closest() only crawls right up the DOM tree, ignoring other child elements. Right? parent() works almost the same and doesn't work either.

And as i only want to toggle the closest .meddel div in the element, i need something that, yeah justs grabs the nearest one, and not all of them.

To clear it up a bit, here's the HTML for one list item:

<li class="item">

<h4><a class="toggle">[topic]</a><small>2010-04-17 kl 12:54 by <u>[name]</u></small></h4>

<div class="meddel">
    <span>
        <img style="max-width: 70%; min-height: 70%;" src="profile-images/img.jpg" alt="" />
        <a href="account.php?usr=47">[name]</a>
    </span>

    <p>text</p>
</div>

</li>

I have several items like that, and if i click one toggle link, i just want the nearest .meddel to be toggled, as mentioned before.

Thanks.


Here's another way to approach this:

$('.pmlist ul li h4 .toggle').click(function() {
  $(this).closest('h4').siblings('.meddel').toggle(250);
});

This goes up to the <h4>, then looks for a sibling .meddel element to toggle. You can read more on .siblings() here. This method keeps it a bit more resilient to markup changes, but if the script is tightly coupled anyway, that may not be much of a concern.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK