レッスンに戻る

外部リンクをオレンジにする

重要性: 3

style プロパティを変更することで、すべての外部リンクをオレンジにしてください。

次のものが外部リンクです:

  • href の中に :// がある場合
  • しかし、http://internal.com から始まらない場合

例:

<a name="list">the list</a>
<ul>
  <li><a href="/?originalUrl=https%3A%2F%2Fja.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%2520%25E5%258D%2598%25E4%25B8%2580%25E3%2583%25AA%25E3%2583%25B3%25E3%2582%25AF%25E3%2581%25AE%2520style%2520%25E3%2582%2592%25E8%25A8%25AD%25E5%25AE%259A%2520%2520let%2520link%2520%3D%2520document.querySelector("a');
  link.style.color = 'orange';
</script>

結果は次のようになるはずです:

タスクのためのサンドボックスを開く

最初に、すべての外部参照を見つける必要があります。

2つの方法があります。

1つ目は document.querySelectorAll('a') を使ってすべてのリンクを見つけ、必要なものをフィルタする方法です:

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

for (let link of links) {
  let href="/?originalUrl=https%3A%2F%2Fja.javascript.info%2Flink.getAttribute("href');
  if (!href) continue; // 属性なし

  if (!href.includes('://')) continue; // プロトコルなし

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

  link.style.color = 'orange';
}

注意してください: link.getAttribute('href') を使っています。 link.href ではありません。なぜなら、 HTML からの値が必要なためです。

…もう1つ、よりシンプルな方法は CSS セレクタにチェックを追加する方法です。:

// href の中に :// を持つリンクを探しますが、href は http://internal.com から始まらないもの
let selector = 'a[href*="://"]:not([href^="http://internal.com"])';
let links = document.querySelectorAll(selector);

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

サンドボックスで解答を開く