Search code examples
javascriptdom-events

JavaScript Elements


I need help with the following:

I have a page with h3-s and paragraphs and I want all the paragraphs to initially be hidden.

If a h3 is clicked, the script will loop through the tags below it, showing the paragraph tags, if it comes to another h3 tag it should break out the loop.

I have no control over the html output so I can't nest the tags or give any of the h3-s ids. The code below is all i have to play with.

E.g. If H3 Title2 is clicked, then Title 2 Para 1 and Title 2 Para 2 are shown, if H3 Title2 is clicked again then Title 2 Para 1 and Title 2 Para 2 are hidden.

<h3>H3 Title1</h3>
<p>Title 1 Para 1</p>
<p>Title 1 Para 2</p>
<p>Title 1 Para 3</p>
<p>Title 1 Para 4</p>


<h3>H3 Title2</h3>
<p>Title 2 Para 1</p>
<p>Title 2 Para 2</p>


<h3>H3 Title3</h3>
<p>Title 3 Para 1</p>
<p>Title 3 Para 2</p>


<h3>H3 Title4</h3>
<p>Title 4 Para 1</p>
<p>Title 4 Para 2</p>
<p>Title 4 Para 3</p>

No jQuery please


Solution

  • Take a look at getElementsByTagName to get all the H3s on your page, you want to attach a click() handler to those.

    In your onclick you loop over all the next elements until you get to an H3 and break out of the loop. Take a look at nextElementSibling for getting the elements after the H3.

    For showing/hiding either set a css class or directly change the element's style toggling between display:block and display:none.