heyitsalec
heyitsalec

Reputation: 300

Select entire container div from deep child in DOM

Is there a way to target a large container div based on an existing child deep within its DOM tree?

In the following example - can we hide blockA based on the fact that a child of blockA has a deep child element with an id called targetA?

  <div class="blockA">
    <span class="title">BlockA</span>
    <div>
      <p id="targetA">
        Delete this whole block, please
        this is a paragraph,
        lorem ipsum
      </p>
    </div>
  </div>
  <div class="blockB">
    <span class="title">BlockB</span>
    <div>
      <p>
        this is a paragraph,
        lorem ipsum
      </p>
    </div>
  </div>
</div>

Upvotes: 1

Views: 407

Answers (1)

Yousaf
Yousaf

Reputation: 29281

You can use Element.closest()

child.closest('.parent')

From MDN

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

You can hide .blockA element by selecting the #targetA element, calling closest method on it and passing the class name of the parent element.

document.getElementById('targetA').closest('.blockA').style.display = 'none';

P.S. you might want to guard against closest function returning null.

Demo:

const target = document.getElementById('targetA');
const button = document.querySelector('button');

button.addEventListener('click', () => {
  const parent = target.closest('.blockA');
  if (parent) parent.style.display = 'none';
});
.blockA,
.blockB {
  background: #fafafa;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
  margin: 10px 0;
}
p { margin: 0; }
.blockA, .blockB, button { padding: 10px; }
<div class="blockA">
  <span class="title">BlockA</span>
  <div>
    <p id="targetA">
      Delete this whole block, please this is a paragraph, lorem ipsum
    </p>
  </div>
</div>
<div class="blockB">
  <span class="title">BlockB</span>
  <div>
    <p>this is a paragraph, lorem ipsum</p>
  </div>
</div>
</div>

<button>Hide BlockA</button>

Upvotes: 1

Related Questions