Select non-adjacent element with jquery

I have an html file which is structured pretty much this way:

<div id="text-container">
   <h1>Title 1</h1>
   <div class="text"></div>
   <div class="text"></div>
   <div class="text"></div>
   <div class="text"></div>
   <h1>Title 2</h1>
   <div class="text"></div>
   <div class="text"></div>
   <div class="text"></div>
   <h1>Title 3</h1>

The files are built dynamically, so number of titles and text-class divs can vary. What I am trying to achieve is to insert a elements in order to be able to jump from one title to the next, so I'm sort of after a prev() or next() but without the elements having to be siblings.

Can anyone please point me in the right direction ?

Thanks in advance for your help


Here it is: using some ternary operators: (just add a class btn to your .prev and .next buttons)

   $(this).data('myTopPosition', $(this).position().top );

var howMany = $('h1').length;
var curr = 0; // zero based so the first 'H1' is actually '0'

function correct(){
    var corr = curr === -1 ? curr=howMany-1 : curr = curr%howMany;

  var whatBtn= $(this).hasClass('next') ? curr++ : curr-- ;
    var goToPos = $('h1').eq(curr).data('myTopPosition');
    $('html, body').stop().animate({ scrollTop: goToPos },1500);

If you want .next() functionality that goes beyond the immediate next element, try .nextUntil + .next

$("#text-container").click(function() {
    var $nextTitle = $(this).nextUntil("h1").next();

Need Your Help

Looping multiple hashtags in php string to insert into database

php regex preg-match-all

I am building a system and wish to allow people to leave comments with hash tags in them, for example "This is an #example #of #what I wish to achieve".

How to read a text file and add the data to a int array in C#?

c# arrays text io

I'm trying to read a text file which contains numbers separated by a comma. When I read using File.Readline() I get it to a string[]. I need to convert it in to a int array but it gives an error.