Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Why this code is not working?

We have multiple lines of a paragraph where I want to show 1 line and show the other lines whenever the more info link is clicked.

<div class="card-body">
    <h6 class="card-title">درباره من</h6>
    <div id="dots" style="height: 12em;" class="overflow-hidden">
        {!! $counseling->body !!}
    </div>
    <div id="moreText" class="d-none">
        {!! $counseling->body !!}
    </div>
    <a id="linkText" href="#" onclick="toggleVisibility();">ادامه</a>
</div>

<script>
    function toggleVisibility() {
        var dots = document.getElementById('dots');
        var moreText = document.getElementById('moreText');
        var linkText = document.getElementById('linkText');

        if (dots.classList === "d-none") {
            dots.style.display = "d-block";
            linkText.textContent = "ادامه";
            moreText.style.display = "d-none";
        } else {
            dots.style.display = "d-none";
            linkText.textContent = "بستن";
            moreText.style.display = "d-block";
        }
    }
</script>
0 likes
2 replies
LaryAI's avatar
Level 58

The issue with the code is that the classList property returns a DOMTokenList object, not a string. Therefore, the if statement in the toggleVisibility function will never evaluate to true. Instead, you should use the contains method to check if the d-none class is present in the classList. Here's the corrected code:

<div class="card-body">
    <h6 class="card-title">درباره من</h6>
    <div id="dots" style="height: 12em;" class="overflow-hidden">
        {!! $counseling->body !!}
    </div>
    <div id="moreText" class="d-none">
        {!! $counseling->body !!}
    </div>
    <a id="linkText" href="#" onclick="toggleVisibility();">ادامه</a>
</div>

<script>
    function toggleVisibility() {
        var dots = document.getElementById('dots');
        var moreText = document.getElementById('moreText');
        var linkText = document.getElementById('linkText');

        if (dots.classList.contains('d-none')) {
            dots.style.display = "none";
            linkText.textContent = "بستن";
            moreText.style.display = "block";
        } else {
            dots.style.display = "block";
            linkText.textContent = "ادامه";
            moreText.style.display = "none";
        }
    }
</script>

Please or to participate in this conversation.