Issue
I am trying different selectors using CSS. I am confused. I want to change only the the links that is pointing to secure sites (https). I want to change the color of secured links. How can I do that?
Here the code containing first two https and the rest one http:
a {
color: #333;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Selectors</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="exercise.css" />
</head>
<body>
<a href="https://www.google.com">Google</a>
<a href="https://www.google.com">Google</a>
<a href="http://www.google.com">Google</a>
</body>
</html>
Solution
Use [href^="https://"]
. Selects all a tags whose href begins with https://
.
a {
color: #333;
font-size: 20px;
}
a[href^="https://"] {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Selectors</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="exercise.css" />
</head>
<body>
<a href="https://www.google.com">Google</a>
<a href="https://www.google.com">Google</a>
<a href="http://www.google.com">Google</a>
</body>
</html>
More info about attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
Unfortunately, some http links have port 443, which also forces HTTPS. It is not possible to style such links with CSS, but you might get some hope with JavaScript:
// Get all links with href attribute
const links = document.querySelectorAll('a[href]');
for (var i = 0; i < links.length; i++) {
const link = links[i];
const href = link.href;
const split = href.replace("http://", "");
const parts = split.split("/");
if (parts[0].endsWith(":443")) {
link.classList.add('red');
}
}
a {
color: #333;
font-size: 20px;
}
a[href^="https://"] {
color: red;
}
.red {
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Selectors</title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="exercise.css" />
</head>
<body>
<a href="https://www.google.com">Google</a>
<a href="https://www.google.com">Google</a>
<a href="http://www.google.com">Google</a>
<a href="http://www.google.com:443">Google</a>
</body>
</html>
Answered By – Someone_who_likes_SE
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0