skip to Main Content

I’m really new to JavaScript.

I have a html like this:

<li><a class="dropdown-item confirm" 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>

3

Answers


  1. function getValue() {
        document.getElementById("staticBackdropLabel").innerText = document.getElementsByTagName("a")[0].innerText;
    }
    <li  onclick="getValue()"><a class="dropdown-item confirm" href="#">wtdata</a></li>
    <h5  id="staticBackdropLabel">You want to run wtdata ?</h5>
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. Add a onClick event to your <a/> tag, then use innerText attribute. like this

    const a = document.getElementById("a");
    a.addEventListener("click", (e) => {
      const staticBackdropLabel = document.getElementById("staticBackdropLabel");
      staticBackdropLabel.innerText = e.target.innerText;
    });
    <li><a id="a" class="dropdown-item confirm" href="#">wtdata</a></li>
    
    <h5 id="staticBackdropLabel">You want to run wtdata ?</h5>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search