0

I'm trying (in native Javascript, so without jQuery or anything) to get content before and after occurence of a div.

HTML:

<div id="thisIsWhatIWant">
  <span>foo</span>
    <div id="helloWorld">hello world</div>
  <p>bar</p>
</div>

So I want to get <span>foo</span> and <p>bar</p> in separate vars.

JS:

var beforeElement_helloWorld = ...do something to get <span>foo</span>...
var afterElement_helloWorld  = ...do something to get <p>bar</p>...

note:
There may be many more divs, spans etc in the HTML example.

Bob van Luijt
  • 7,153
  • 12
  • 58
  • 101

1 Answers1

3

You need this:

var previous = document.getElementById("helloWorld").previousElementSibling;
var next = document.getElementById("helloWorld").nextElementSibling;

Also read this, The difference between previousSibling and previousElementSibling, is that previousSibling returns the previous sibling node as an element node, a text node or a comment node, while previousElementSibling returns the previous sibling node as an element node (ignores text and comment nodes).

roshan
  • 2,410
  • 2
  • 25
  • 37
  • Fantastic @roshan this is *exactly* what I'm looking for. I love jQuery, but I don't know all these native JS possibilities. – Bob van Luijt Feb 24 '15 at 01:44