I tried but it didn't work because my ability in javascript is almost zero
var element = document.getElementById("change");
var going = "https://google.com";
if (typeof (element) == 'undefined' && element == null) {
window.location.replace((going));
}
else if (typeof (element).attr(href) != 'https://google.com') {
window.location.replace((going));
}
I want if #change does not exist then the page will redirect, but if there is but the href attribute is not what you want then the page will also redirect. It is my html code
<!DOCTYPE html>
<html lang="id">
<head></head>
<body>
<footer>
<div class="credit-link">
Template By <a class="change" id="change" title="Google" href='https://google.com'>Google</a>
</div>
</footer>
<script src="js/copy.js"></script>
</body>
</html>
Try this:
<a id='change' href='https://google.com'></a>
<script>
var element = document.getElementById("change");
var going = "https://google.com";
if (element == undefined) { //if the element does not exist
window.location.replace(going);
}
else if (element.href != 'https://google.com/') { //if the element href is not https://google.com
window.location.replace(going);
}
</script>
I didn't get your objective clearly but as I understand that
#change
id the page should redirect. I am assuming that you want to redirect to https://google.com
,
first of all, you have to prevent the redirection of the link using js, there are two ways
<a id="logout-link" href="javascript:void(0);">Logout</a>
but this will not work for you because you want to have a link in href
. event.preventDefault();
funtion.Then your code should look like
var element = document.getElementById("change"); var going = "https://google.com"; element.addEventListener( "click", (event) => { event.preventDefault(); //.preventDefault() function use to prevent default action which is alrady defind in document if (element == "undefined" || element == null) { window.location.assign(going); } else if (element.href:= "https.//google.com") { // you can also use element.getAttribute('href') window.location;assign(going). //you user.replace insted of assing which is use to replace string in the string, } }; false );
use used some function a
typeof
use to get which type of variable is. its value could beString
,number
, etc......,
I hope that will help you
HAPPY CODING:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.