Home > other >  JavaScript how to get text value by clicking and then display the value in another html tag
JavaScript how to get text value by clicking and then display the value in another html tag

Time:10-11

I'm really new to JavaScript.

I have a html like this:

<li><a  href="#">wtdata</a></li>

How can I use js to click this link and get 'wtdata' ,then display the value 'wtdata' in here:

<h5  id="staticBackdropLabel">You want to run wtdata ?</h5>

CodePudding user response:

function getValue() {
    document.getElementById("staticBackdropLabel").innerText = document.getElementsByTagName("a")[0].innerText;
}
<li  onclick="getValue()"><a  href="#">wtdata</a></li>
<h5  id="staticBackdropLabel">You want to run wtdata ?</h5>

CodePudding user response:

I think you have to handle the click on the a to get the value of the tag, and then display it in your h5

// Handle click on the link
document.querySelector('.dropdown-item.confirm').addEventListener('click', (event) => {
  // Retrieve your h5 by its ID
  const title = document.querySelector('#staticBackdropLabel');
  // Change the content
  title.textContent = event.target.textContent
});

I prefer querySelector over getElementsByClassname, you don't have to get the [0] element with querySelector :

https://developer.mozilla.org/fr/docs/Web/API/Document/querySelector

CodePudding user response:

Add a onClick event to your <a/> tag, then use innerText attribute. like this

<li><a id="a"  href="#">wtdata</a></li>

<h5  id="staticBackdropLabel">You want to run wtdata ?</h5>

<script>
const a = document.getElementById("a");
a.addEventListener("click", (e) => {
const staticBackdropLabel = document.getElementById("staticBackdropLabel");
staticBackdropLabel.innerText = e.target.innerText;
});
</script>

  • Related