Details:
Hi experts. I want to change an existing HTML theme using only javascript, and I have problem in changing HTML element's href using javascript. But it seems I can't even get the elements by ClassName because the console.log value of javascript code below shows 0 length. Please help how should I fix the code. (Note that I can't edit the existing HTML code, only can write custom code of javascript). Best regards
My javascript is as below:
var x8 = document.getElementsByClassName("slrofrpg-srvcs-backbtn");
console.log("length=",x8.length); --1st console
if (x8.length > 0){
console.log("ENTERED. length=", x8.length); --2nd console
x8[0].href = "javascript:history.back()";
}
My HTML is as below (some part of it):
<div class="slrofrpg-service-btn">
<a class="slrofrpg-srvcs-backbtn" href="javascript:void(0);">Back
</a>
<!-- react-text: 219 -->
<!-- /react-text -->
<a class="slrofrpg-srvcs-offerbtn" href="javascript:void(0);">Send now
</a>
</div>
1st console log result:
length=0
2nd console log result: No result
The code is working fine here. Your script is running before the the loading of html.You can
<script>
tag at end of the <body>
window.onload
event window.onload = function(){ var x8 = document.getElementsByClassName("slrofrpg-srvcs-backbtn"); console.log("length=",x8.length); if (x8.length > 0){ console.log("ENTERED. length=", x8.length); x8[0].href = "javascript:history.back()"; } }
<div class="slrofrpg-service-btn"> <a class="slrofrpg-srvcs-backbtn" href="javascript:void(0);">Back </a> <!-- react-text: 219 --> <!-- /react-text --> <a class="slrofrpg-srvcs-offerbtn" href="javascript:void(0);">Send now </a> </div>
It seems you are running the javascript before the dom is loaded. Add javascript or add the external js file near the closing end of body tag
<body>
// html code
<script>
//js code here
</script>
</body>
var x8 = document.getElementsByClassName("slrofrpg-srvcs-backbtn"); console.log("length=", x8.length); if (x8.length > 0) { console.log("ENTERED. length=", x8.length); x8[0].href = "javascript:history.back()"; }
<div class="slrofrpg-service-btn"> <a class="slrofrpg-srvcs-backbtn" href="javascript:void(0);">Back </a> <!-- react-text: 219 --> <!-- /react-text --> <a class="slrofrpg-srvcs-offerbtn" href="javascript:void(0);">Send now </a> </div>
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.