I have given code below. I want that a variable of JS take anchor tag text as input and display in another Element through innerHTML.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p><a class="myAnchor" href="http://www.microsoft.com">www.microsoft.com</a>
<a class="myAnchor" href="http://www.microsoft.com">www.microsoft.com</a></p>
<p>Click the button to change the value of the href attribute of the link above to "www.cnn.com".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var x=$(".myAnchor").on("click",function(event){
event.preventDefault();
$(this).text();
});
function myFunction() {
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
What you are doing wrong?
Instead of assigning the click event to a variable, assign the inner text of the clicked link in a variable and on clicking the button assign this variable to the required element.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <p> <a class="myAnchor" href="http://www.microsoft.com">www.microsoft.com1</a> <a class="myAnchor" href="http://www.microsoft.com">www.microsoft.com2</a> </p> <p> Click the button to change the value of the href attribute of the link above to "www.cnn.com". </p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var x = ''; $(".myAnchor").on("click", function(event) { event.preventDefault(); x = $(this).text(); }); function myFunction() { document.getElementById("demo").innerHTML = x; } </script> </body> </html>
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.