How to get JavaScript href on button click?

  • 0
    Made this code in jquery, but how to translate it into pure js?
    How to get the href value when clicking on the menu-item-text class
    $('.menu-item-text').click(function(){
    
    	let b = $(this).attr('href').replace('#', '');
    	$('[name="'+b+'"]').scrollIntoView({block: "center", behavior: "smooth"})
    	})
    JavaScript Anonymous, Jul 13, 2019

  • 4 Answers
  • 0
    document.querySelector('.menu-item-text').addEventListener("click", (e) => {
    const elem = e.target.getAttribute('href').replace('#', '');
    document.querySelector(`[name="${elem}"]`).scrollIntoView({block: "center", behavior: "smooth"});
    });
    Eliot Harrington

  • 0
    const handleClick(el) {
    const href = el.target.getAttribute('href').replace('#', '');
    document.querySelector(`[name="${href}"]`).scrollIntoView({block: "center", behavior: "smooth"});
    };
    document.querySelectorAll('.menu-item-text').forEach(el => el.addEventListener('click', handleClick));
    Anonymous

  • 0
    document.addEventListener('click', function myClickHandler(evt) {
    const menuItem = evt.target.closest('.menu-item-text');
    if (menuItem) {
    const b = menuItem.href.hash.replace('#', '');
    console.log(b);
    }
    });
    Anonymous

  • 0
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!