I want to create a script that changes the href of a button only if it contains a link or a period, since URLs normally contain periods (if it contains a link, I want to replace it with another one, for example google.com). However, the script I have changes all hrefs regardless of their content.
<script>
window.onload = function() {
var anchors = document.getElementsByClassName("elementor-button");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "https://google.com"
}
}
</script>
3
Answers
Add validation based on your constraints & replace the href accordingly.
if (href && href.includes("."))
:href
attribute).href.includes(".")
: The href contains a period (.), which is typical in URLs or replace this with your actual constraints.if both conditions are met, then the script replace the
href
with "https://google.com" or any url.You can use
string.includes()
to see if thehref
includes a dot.Below is the final code, however, as the
href
on an anchor in an SO snippet has the default domain of SO, it doesn’t work correctly in the snippet – demonstrational snippet is below.Demonstrational snippet
Script that only changes the href if it already contains a dot, which is common in URLs