0

I am unable to change any html on the website in question.

Here is some html:

<ul id="utility-menu" class="menu menu--primary">

        <li><a class="" href="https://www.example.com/newsstand" target="_blank">Magazines</a></li>

        <li><a class="" href="https://secure.bla.com/example/promo/GiveAGift/" target="_blank">Gifts</a></li>

        <li>

          <a href="/email_check?lang=fr">Français</a>
        </li>

            <li><a class="" href="/signin">Sign In</a></li>

        <li>
          <div class="i-am-canadian">
            <img alt="Canadian flag" height="23px;" src="https://secure.example.com/assets/images/icons/ui/i-canadian-c8a132ad64588dcc0b2e61cc589dfef3.png" width="40px;">
          </div>
        </li>
      </ul>

I managed to select the menu using:

document.querySelectorAll('.menu--primary')[0]

The element I'm interested in is:

<a href="/email_check?lang=fr">Français</a>

This element i a language selection for the site visitor that will be either "English" or "Français".

If the user is on an English language page the value of the element will be that shown. But if they are on the French language equivalent the element will be <a href="/email_check?lang=en">English</a>

I would like a selector that returns either "English" or "Français".

How would I do that?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

2 Answers2

2

Answer:

var el = document.querySelector('#utility-menu a[href^="/email_check?lang="').textContent;

It will select first a element with attribute href begining with /email_check?lang= in #utility-menu. Probably you can .trim() text to get rid of whitespaces.

Ginden
  • 5,149
  • 34
  • 68
  • This is great, thank you very much. What is the hat ^ doing next to the equals sign? – Doug Fir Aug 02 '15 at 15:15
  • 2
    @DougFirr it matches attribute whose value begins with the given prefix http://stackoverflow.com/questions/16791527/can-i-use-a-regular-expression-in-queryselectorall – Amitd Aug 02 '15 at 15:31
1

If your html is not going to change much, you can use

var test = document.querySelector("ul > li > a[href='/email_check?lang=fr']");

console.log(test.textContent); // Français

https://jsfiddle.net/u4vjq8ah/

Amitd
  • 4,769
  • 8
  • 56
  • 82