外部リンクをオレンジ色にする
重要性: 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.dokyumento.jp">https://node.dokyumento.jp</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>
結果は次のようになります。
最初に、すべての外部リンクを見つける必要があります。
2 つの方法があります。
1 つ目は 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';
}
注意: HTML から値が必要なので、link.getAttribute('href')
を使用します。link.href
は使用しません。
…もう 1 つのより簡単な方法は、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');