Question

I have a question. I have this html. In the readmore box, there is a lot of content. And i how more .readmore-open links and readmore boxes on the web page.

<p>
<a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder" class="readmore-open">Lees verder</a>
</p>

<div class="readmore-box">

</div>

Now my question. When you click the .readmore-open link. The first readmore-box what then coming, must be show. I have this script. What i am doing wrong.

$('.readmore-open').click(function(e){
    $(this).closest('.readmore-box').toggleClass('active');
})
Was it helpful?

Solution

$('.readmore-open').click(function(){
    $(this).closest('p').next('.readmore-box').toggleClass('active');
});

Your DOM traversal was a bit off.

OTHER TIPS

.closest() only looks up the DOM tree for ancestors of the currently selected node(s). In this case, .readmore-box is not an ancestor and won't be found.

Currently, the way you have structured your HTML, you would require going up to the parent and then looking for the next sibling. You may consider restructuring your HTML a bit to make the DOM traversal more reliable. For example if you had element at same level as siblings you could use .next() to find the next sibling.

So for example, by moving up class declaration to containing <p>. You can do this:

HTML:

<p class="readmore-open">
    <a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder">Lees verder</a>
</p>
<div class="readmore-box">...</div>

Javascript:

$('.readmore-open').click(function(e){
    $(this).next('.readmore-box').toggleClass('active');
})

Another approach would be to provide a common ancestor you can rely upon

HTML:

<div class="readmore">
    <p>
        <a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder" class="readmore-open">Lees verder</a>
    </p>
    <div class="readmore-box">...</div>
</div>

Javascript:

$('.readmore-open').click(function(e){
    $(this).closest('.readmore').find('.readmore-box').toggleClass('active');
})

This second approach would probably be more flexible, in that you could have the .readmore-box pretty much anywhere inside that common ancestor (before the link, on a different hierarchy level than the link, etc.).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top