Open Closest div on link function in jquery

Please great hands,
I need help in getting the closest div to open of show when a link is clicked.

Below is my codes.

// Html
<a href="#0006" class="view-more">view more</a>
<div class="description">This content is for the ref link 0006</div>

<a href="#0007" class="view-more">view more</a>
<div class="description">This content is for the ref link 0007</div>

<a href="#0008" class="view-more">view more</a>
<div class="description">This content is for the ref link 0008</div>

// Css
.description {
display: none;
}


// Jquery
$('.view-more').on("click", function (){
$('.description').toggle();
});

But the problem is when the view link is clicked only the first line which if 0006 works others is not working.

And if i do

$('a.view-more').on("click", function (){ 
$('.description').toggle();
});

Any link clink will open all description or open only description for 0006

But what i want to achieve is that when a link is clicked it should only show description div related to that link alone.

.next() | jQuery API Documentation

2 Likes

@m_hutley thanks but i tried the .next() and .closest() none is giving me what i want. maybe am not using them right.

$('.view-more').on('click', function (){
next('div').toggle ();
}

Maybe $(this).next():

// Jquery
$(".view-more").on("click", function () {
  $(this).next($(".description")).toggle();
});

or Just:

$(".view-more").on("click", function () {
  $(this).next().toggle();
});

Thanks but for some reasons when i use $(this) everything stop working

Works for me:

What does your whole code look like.

yeah it worked in the code pen shown above let me figure out whats happening at my own end

1 Like

Breakpoint the code inside your function and check what $(this) evaluates to in the console.

2 Likes

I think my problem is that i wrapped both the link and more div inside a div.

something like this

<div class="holder">
<span><a href="#">view more</a></span>
<div class="description">Content for this link 0006</div>
</div>

i think is not evaluating to anything, bcs the html came from a while loop in php and may have multiple div joined together, so i will view the source page and see what it looks like and where am missing it

writing the html plainly works with the code @PaulOB and @m_hutley provided but in a while loop i think the display is different when rendered

You don’t have the view-more class on the anchor and then you would need to change the js to go up one level and then find next().

e.g.

$(".view-more").on("click", function () {
  $(this).closest("span").next().toggle();
});

Rather than leaving things to chance would it not be better to give ids to the divs and use the href in the anchor to point to the div and it will find it no matter what you put in the way.

e.g.

1 Like

Thanks alot, it worked.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.