Search code examples
javascripthtmlparentchildren

How can I disable links inside a certain class using JS?


I need a script that will disable all links inside the "parent" .my-class using Vanilla JS (without jQuery):

<div class="my-class">
    <div class="class-1">
        <div class="class-2">
            <div class="class-3">
                <a href="#">
                    <div class="class-4"></div>
                </a>
                <a href="#">
                    <div class="class-4"></div>
                </a>
                <a href="#">
                    <div class="class-4"></div>
                </a>
            </div>
        </div>
    </div>
</div>

UPD: I need links that can't be clicked on. It doesn't matter if the "href" entry remains or not.


Solution

  • You can check the answers on this entry, I think they will help: How do I disable a href link in JavaScript?

    But, basically, you have two options:

    1. Avoid the "href" attribute from having a value

      1.1. Remove the attribute alltogether: parentElement.querySelectorAll('a').forEach(link => link.removeAttribute("href"));

      1.2. Set the value to "javascript:void(0)": parentElement.querySelectorAll('a').forEach(link => link.setAttribute("href", "javascript:void(0)"));

    2. Prevent click events from being fired:

    parentElement.querySelectorAll('a').forEach(link => link.style.pointerEvents = "none")