返回課程

將外部連結設為橘色

重要性:3

透過變更 style 屬性,將所有外部連結設為橘色。

如果連結符合下列條件,則為外部連結

  • href 中包含 ://
  • 但開頭不是 http://internal.com

範例

<a name="list">the list</a>
<ul>
  <li><a href="http://google.com">http://google.com</a></li>
  <li><a href="/tutorial">/tutorial.html</a></li>
  <li><a href="local/path">local/path</a></li>
  <li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
  <li><a href="https://node.dev.org.tw">https://node.dev.org.tw</a></li>
  <li><a href="http://internal.com/test">http://internal.com/test</a></li>
</ul>

<script>
  // setting style for a single link
  let link = document.querySelector('a');
  link.style.color = 'orange';
</script>

結果應為

為此任務開啟沙盒。

首先,我們需要找出所有外部連結。

有兩種方法。

第一種方法是使用 document.querySelectorAll('a') 找出所有連結,然後篩選出我們需要的部分

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

for (let link of links) {
  let href = link.getAttribute('href');
  if (!href) continue; // no attribute

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

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

  link.style.color = 'orange';
}

請注意:我們使用 link.getAttribute('href'),而不是 link.href,因為我們需要 HTML 中的值。

…另一種更簡單的方法是將檢查加入 CSS 選擇器

// look for all links that have :// in href
// but href doesn't start with http://internal.com
let selector = 'a[href*="://"]:not([href^="http://internal.com"])';
let links = document.querySelectorAll(selector);

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

在沙盒中開啟解答。