Haz los enlaces externos naranjas
importancia: 3
Haz todos los enlaces externos de color orange alterando su propiedad style.
Un link es externo si:
- Su
hreftiene:// - Pero no comienza con
http://internal.com.
Ejemplo:
<a name="list">the list</a>
<ul>
<li><a href="/?originalUrl=https%3A%2F%2Fes.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%2520establecer%2520un%2520estilo%2520para%2520un%2520enlace%2520%2520let%2520link%2520%3D%2520document.querySelector("a');
link.style.color = 'orange';
</script>
El resultado podría ser:
Primero, necesitamos encontrar todos los enlaces externos.
Hay dos.
El primero es encontrar todos los enlaces usando document.querySelectorAll('a') y luego filtrar lo que necesitamos:
let links = document.querySelectorAll('a');
for (let link of links) {
let href="/?originalUrl=https%3A%2F%2Fes.javascript.info%2Flink.getAttribute("href');
if (!href) continue; // no atributo
if (!href.includes('://')) continue; // no protocolo
if (href.startsWith('http://internal.com')) continue; // interno
link.style.color = 'orange';
}
Tenga en cuenta: nosotros usamos link.getAttribute('href'). No link.href, porque necesitamos el valor del HTML.
…Otra forma más simple sería agregar las comprobaciones al selector CSS:
// busque todos los enlaces que tengan: // en href
//pero href no comienza con http://internal.com
let selector = 'a[href*="://"]:not([href^="http://internal.com"])';
let links = document.querySelectorAll(selector);
links.forEach(link => link.style.color = 'orange');