외부 링크를 주황색으로 만들기
중요도: 3
style 프로퍼티를 변경해 모든 외부 링크를 주황색으로 만들어 보세요.
외부 링크가 되기 위한 조건은 아래와 같습니다.
href에://가 포함되어 있어야 합니다.- 하지만
http://internal.com으로 시작하지 않아야 합니다.
예시:
<a name="list">the list</a>
<ul>
<li><a href="/?originalUrl=https%3A%2F%2Fko.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>
결과:
먼저 외부 참조를 모두 찾아야 합니다.
두 가지 방법을 사용해 외부 참조를 찾을 수 있습니다.
첫 번째 방법은 document.querySelectorAll('a')를 사용해 모든 링크를 찾은 후 필요한 것만 걸러내는 것입니다.
let links = document.querySelectorAll('a');
for (let link of links) {
let href="/?originalUrl=https%3A%2F%2Fko.javascript.info%2Flink.getAttribute("href');
if (!href) continue; // 속성이 존재하지 않음
if (!href.includes('://')) continue; // 프로토콜이 존재하지 않음
if (href.startsWith('http://internal.com')) continue; // 내부 링크
link.style.color = 'orange';
}
참고: HTML의 값이 필요하기 때문에 link.href가 아니라 link.getAttribute('href')를 사용합니다.
더 간단한 방법은 CSS 선택자에 조건을 명시해 주는 것입니다.
// 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');