skip to Main Content

i need to add onclick="window.location.href= to all elements on my page
I heard i need to use * for all elelemts
how will code look for me to make that? hope someone can help me

will aprecte help so much, im new to programming, just learning

2

Answers


  1. if you want to add a click event for all buttons, something like this will work:

      Array.from(document.querySelectorAll("button")).forEach((c) => {
        c.addEventListener("click", function (event) {
            window.location.href="website.com";
        });
      });
    
    Login or Signup to reply.
  2. To answer your question directly, to add window.location.href = "https://example.com" to every element on your page, you need to use the * selector, as you mentioned. That will look something like this:

    document.querySelectorAll('*').forEach(element => {
        element.addEventListener('click', () => {
            window.location.href = 'https://website.com';
        });
    });
    

    That being said, it seems unnecessary to attach a click event to every single element, and probably makes more sense to attach the click event to the body element or the page itself.

    document.body.addEventListener('click', () => {
        window.location.href = 'https://website.com';
    });
    
    document.documentElement.addEventListener('click', () => {
        window.location.href = 'https://website.com';
    });
    

    If you simply meant you wanted to add it to every link or button on your page, and not actually every element, then something like this would work:

    You can substitute ‘a’ and ‘button’ in the code below with any element that you want to apply the click event to.

    const clickableElements = document.querySelectorAll('a, button');
    clickableElements.forEach(element => {
        element.addEventListener('click', (event) => {
            event.preventDefault();
            window.location.href = 'https://website.com';
        });
    });
    

    Another method for catching the click event on multiple buttons is to add a click event to their parent div, and then check if the child element being clicked is a button.

    const parentElement = document. getElementsByTagName('body');
    parentElement.addEventListener('click', (event) => {
      const isButton = event.target.nodeName === 'BUTTON';
      if (!isButton) {
        return;
      }
      window.location.href = 'https://website.com';
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search