Search code examples
javascripthtmldomselectors-api

Get all the elements id after a targeted element


So how can I get all the elements after a targeted element for example I want to get all the elements after the id call c regardless of the quantity of elements that is after c

For example

d
e
f

and I want to output the result in a id element call output

This is my code i'm stuck on

/*
Get all the elements ids after the id call c and output those 
ids in the id call output 

For example 
document.querySelector('#output').innerHTML = ??;

How?
*/
#output{
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>


Solution

  • No offense to others examples here but I notice some code examples here will have some compatibility issues on certain browsers like

    IE 11 so this works on all the major browsers that I tested this on. Just in case if your trying to get this to work on IE 11 so here is my example...

    var afterC = [].slice.call(document.querySelectorAll('#c ~ *.letters')).map(function(elem){ return elem.getAttribute('id');});
    
    document.querySelector('#output').innerHTML = afterC;
    #output{
      color: red;
    }
    <h1 id='a' class='letters'>A</h1>
    <h1 id='b' class='letters'>B</h1>
    <h1 id='c' class='letters'>C</h1>
    <h1 id='d' class='letters'>D</h1>
    <h1 id='e' class='letters'>E</h1>
    <h1 id='f' class='letters'>F</h1>
    
    <h1 id='output'></h1>