V
V
VyacheslavIny2020-04-25 14:42:29
JavaScript
VyacheslavIny, 2020-04-25 14:42:29

Why doesn't target.closest select element by class?

<div class="news-card-1 commentary-closed">
            <div class="news-card-pic"></div>
            <div class="news-card-right">
                <div class="news-card-description">
                    <h1>What is Lorem Ipsum?</h1>
                    <p>Lorem Ipsum is simply dummy text of ...</p>
                </div>
                <div class="news-card-buttons">
                    <div class="news-card-hashtag">
                        <p data-hashtag>#Art</p>
                    </div>
                    <div class="card-buttons">
                        <button type="button" class="heart" value="17"></button>
                        <button type="button" class="list"></button>
                        <button type="button" class="commentary commentary-empty"></button>
                    </div>
                </div>
            </div>
        </div>

document.addEventListener('click', openCommentary);

function openCommentary(event) {
    if (event.target.classList.contains('commentary')) {
        let picture = event.target.closest('.news-card-pic');
        console.log(picture);
    }
}

I'm trying to manipulate the picture by clicking on the button, but event.target.closest('.news-card-pic') returns null to the console .
Tell me why the search by class does not work in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-04-25
@VyacheslavIny

Obviously, because among the ancestors of target there is no element with the specified class. Look carefully where the target is, and where is what you are trying to get.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question