Home › Forums › JavaScript › Learning JS › Reply To: Learning JS
September 22, 2014 at 2:14 pm
#184158
Participant
Ok, how does your script know only to look for an article?
It’s looking for the button’s parent element, which is the article in my demo. Remember when we were talking about what .parentNode
does?
If your HTML looks like this:
<div class='commentbox'>
<p>Hey, I'm the new user!</p>
<span class='detail1' data-username='newuser'>newuser</span>
<button>Click</button>
</div>
Then to find data-username
from the button event, you’d do
var username =
// button that was clicked
event.target
// parent element (the article)
.parentNode
// child element with data-username attribute
.querySelector('[data-username]')
// "newuser"
.getAttribute('data-username');