1

i want to ask how to select the element properly. When i click on the icon it gives me the i tag element but is nested inside an anchor tag. Which approach is correct:

// First Approach
if(e.target.parentElement.dataset.role === 'edit') {
 // Do something
}

// Second Approach
if(e.target.dataset.role === 'edit') {
 // Do something
}

<li>
 <a href="#" class="secondary-content" data-role="edit"> <!-- Parent element -->
  <i class="fa fa-pencil"></i> <!-- nested edit icon -->
 </a>
</li>

2 Answers 2

3

The target property of the event object will be the element that was clicked on.

Use currentTarget to get the element to which the event handler was bound.

document.querySelector("button").addEventListener("click", handler);

function handler(event) {
  console.log(event.currentTarget.dataset.role);
}
span {
  background: yellow
}
<ul>
  <li>
    <button data-role="edit">
      Click Me
      <span>Click Me</span>
     </button>
  </li>
</ul>

Sign up to request clarification or add additional context in comments.

Comments

-1

You can simply add a unique id to your i element, <i id=“some-id ” class=“fa fa-pencil”> and could do something like:

document.querySelector(‘#some-id’)

Or

document.getElementById(‘some-id’)

Or

document.querySelector(‘a i.fa-pencil’) or something like that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.