简体   繁体   中英

Seeking a selector for child elements in dom scrape

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 ia 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?

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM