Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Learning JS Reply To: Learning JS

#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');