retour au cours

Rendre les liens externes orange

importance: 3

Mettez tous les liens externes en orange en modifiant leur propriété style.

Un lien est externe si :

  • Son href contient ://
  • Mais ne commence pas par http://internal.com.

Exemple :

<a name="list">the list</a>
<ul>
  <li><a href="/?originalUrl=https%3A%2F%2Ffr.javascript.info%2F%26quot%3Bhttp%3A%2F%2Fgoogle.com%26quot%3B%26gt%3Bhttp%3A%2F%2Fgoogle.com%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3B%2Ftutorial%26quot%3B%26gt%3B%2Ftutorial.html%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Blocal%2Fpath%26quot%3B%26gt%3Blocal%2Fpath%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Bftp%3A%2F%2Fftp.com%2Fmy.zip%26quot%3B%26gt%3Bftp%3A%2F%2Fftp.com%2Fmy.zip%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Bhttp%3A%2F%2Fnodejs.org%26quot%3B%26gt%3Bhttp%3A%2F%2Fnodejs.org%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%2520%2520%26lt%3Bli%26gt%3B%26lt%3Ba%2520href%3D%26quot%3Bhttp%3A%2F%2Finternal.com%2Ftest%26quot%3B%26gt%3Bhttp%3A%2F%2Finternal.com%2Ftest%26lt%3B%2Fa%26gt%3B%26lt%3B%2Fli%26gt%3B%26lt%3B%2Ful%26gt%3B%26lt%3Bscript%26gt%3B%2520%2520%2F%2F%2520setting%2520style%2520for%2520a%2520single%2520link%2520%2520let%2520link%2520%3D%2520document.querySelector("a');
  link.style.color = 'orange';
</script>

Le résultat devrait être :

Open a sandbox for the task.

Tout d’abord, nous devons trouver toutes les références externes.

Il y a deux façons.

La première consiste à trouver tous les liens à l’aide de document.querySelectorAll('a') puis à filtrer ce dont nous avons besoin :

let links = document.querySelectorAll('a');

for (let link of links) {
  let href="/?originalUrl=https%3A%2F%2Ffr.javascript.info%2Flink.getAttribute("href');
  if (!href) continue; // pas d'attribut

  if (!href.includes('://')) continue; // pas de protocol

  if (href.startsWith('http://internal.com')) continue; // interne

  link.style.color = 'orange';
}

Veuillez noter: nous utilisons link.getAttribute('href'). Pas link.href, car nous avons besoin de la valeur HTML.

… Un autre moyen plus simple serait d’ajouter les contrôles au sélecteur CSS :

// recherchez tous les liens qui ont :// dans href
// mais href ne commence pas par http://internal.com
let selector = 'a[href*="://"]:not([href^="http://internal.com"])';
let links = document.querySelectorAll(selector);

links.forEach(link => link.style.color = 'orange');

Ouvrez la solution dans une sandbox.