0

I am trying to translate these few lines of jQuery based code into vanilla JS but I am struggling. Can someone please explain how to do it?

  function googletranslate() {
    $(".footer-toggle li, .select-lng li").on("click", function() {
      var rel = $(this).children("a").attr("rel");
      $(".goog-te-menu-frame:first").contents().find(".goog-te-menu2 .goog-te-menu2-item span:contains('" + rel + "')").get(0).click();
    });
  }

  setTimeout(googletranslate, 1000);

I know how to do a click event with javascript but im having a hard time finding the element (Just started learning).

<a href="#" rel="Spanish" title="Spanish">Spanish</a>

Basically when the link is clicked, it feeds through rel value to the hidden google translate widget, and simulates a click on the desired language.

Can someone explain how please? Would it be easier to use a select box and get the value from that instead?

1
  • you can use document.querySelector and .querySelectorAll to use complex css selectors like jQuery Commented Mar 24, 2018 at 18:33

2 Answers 2

1
document.querySelector('a[rel="Spanish"]')

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Sign up to request clarification or add additional context in comments.

Comments

0
function googletranslate() {
  ['.footer-toggle li', '.select-lng li'].forEach(selector => {
    const elm = document.querySelector(selector);
    elm.addEventListener('click', clickHandler);
  });

  function clickHandler(e) {
    const rel = e.target.querySelector('a').getAttribute('rel');
    const someGoogleSpan = document.querySelector(".goog-te-menu-frame:first")
      .querySelectorAll(".goog-te-menu2 .goog-te-menu2-item span:contains('" + rel + "')")[0];
    someGoogleSpan.click();
  }
}

setTimeout(googletranslate, 1000);

5 Comments

Thanks for the answer, look's promising but doesn't work. WebPack reported syntax errors, and after fixing those, it says clickHandler is not defined.
Ah! Well spotted. Getting a new error now, Cannot read property 'addEventListener' of null, which probably means its failing to find the elements?
I'm using the selectors you posted in the question, if they don't reflect your HTML structure then you need to figure out which elements you want to select instead. For example <div id="translate-button">Translate</div> then select with '#translate-button'.
Nothing wrong with the html structure, but i think it will work I keep messing, thanks.
Seems its only finding the first li element, not all the LI elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.