-1

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.

baslie
  • 55
  • 1
  • 5
  • How about just a CSS-based solution? i.e. `pointer-events: none` – Irfanullah Jan Aug 19 '22 at 05:32
  • 4
    What do you mean with "disable"? Should they still look like links, but just not clickable, or should the hyperlink rendering be removed, or should the click events be ignored, or should the `a` tags be removed? Should it be temporary, so that it can be restored with another function? – trincot Aug 19 '22 at 05:42

2 Answers2

2

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")

Vigil
  • 64
  • 1
  • 4
0

you can remove the href attribute or its value

links = document.querySelectorAll('.my-class a');
Array.from(links).forEach(element => {
    element.setAttribute('href', '#');
});
Gibon
  • 64
  • 5