PalakM
PalakM

Reputation: 321

Select Element from DOM which is not sibling of selected e

I have span element selected and I want to traverse to input:checkbox. I have tried using next(),nextAll(),nextElementSibling. But as input element is not sibling of span it is not working. Any other way I can select the input element?

Below is my code:

<span>This element is selected via javascript</span>

<div>
  <a href="some link"></a>
</div>


<div class="mb_content">
  5 attachement
  <br />
  <span class="error_star mr_1"><b>Size:5 MB</b></span>
</div>

<div class="checker f_left">
  <label for="rec_787128222">&nbsp;</label>
  <input type="checkbox" class="mb_check" /><!--i want to select this-->
</div>

PS: Actual structure is bit different but I can not paste it over here. This is kind of replica for it.

Upvotes: 2

Views: 83

Answers (3)

radyz
radyz

Reputation: 1714

Without any checks for null, you can try this:

document.querySelectorAll('.error_star.mr_1')[0].parentNode.nextElementSibling.children[1];

Upvotes: -1

Ivan
Ivan

Reputation: 40768

If you really want to use nextSibling()...

var el  = document.querySelector("#foo").nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.children[1];

el.style.display = 'none';
<span id="foo">This element is selected via javascript</span>

<div>
  <a href="some link"></a>
</div>


<div class="mb_content">
  5 attachement
  <br />
  <span class="error_star mr_1"><b>Size:5 MB</b></span>
</div>

<div class="checker f_left">
  <label for="rec_787128222">&nbsp;</label>
  <input type="checkbox" class="mb_check" />
  <!--i want to select this-->
</div>

Upvotes: 1

Naftali
Naftali

Reputation: 146350

You can go to the parent element of the selected DOM element and then select the input.

Try it like this:

// <the element> . <the parent> . <select the input element>
element.parentNode.querySelector('.mb_check')

Upvotes: 2

Related Questions