Search code examples
javascriptjquerydomjquery-selectorstraversal

Jquery tranversing DOM to find consecutives values


Thanks for looking, all helpful answers are voted up. This is my markup. I'm trying to find 2 consecutive divs cmk1 and cmk2 with the content RIGHT and HERE in consecutive order.

  • div id 1 shouldn't match because there's a right but not here.
  • div id 3 shouldn't match because there's a here but no right.
  • I'm trying to find something that looks like div id 2 where right is followed by here. Also the text has to be exact: <div>more than right</div> should not match even though it contains the word right

What's the most efficient way to do this?

Update: I just had a thought, I could find each class=cmk1. if it matches RIGHT, I could select its next (cmk2) and if it matches also, that's what I'm looking for. But how do I do this while loop in jquery? and most importantly how do I exit out of it?

<div class="sep" id="1">
  <div class="cmk1">right</div>
  <div class="cmk2">valc</div>
  <div class="opp">vald</div>   
  <a class="go">Go</a>                  
</div>
<div class="clear">
<div class="sep" id="12">
  <div class="cmk1">RIGHT</div>
  <div class="cmk2">HERE</div>
  <div class="opp">vala</div>   
  <a class="go">Go</a>                  
</div>
<div class="clear">
<div class="sep" id="59">
  <div class="cmk1">vale</div>
  <div class="cmk2">valf</div>
  <div class="opp">here</div>   
  <a class="go">Go</a>                  
</div>
<div class="clear">

Solution

  • $('div.sep > div').each(function() {
        if($(this).text() == 'RIGHT') {
            if($(this).next('div').text() == 'HERE') {
                alert('Values occur consecutively in div id: ' +  $(this).parent().attr('id'));
                return false;            
            }
        }
    });
    

    I've basically looped over all the child divs of the each .sep div and tested for the first word. If it is matched, next can be used to determine if the next div contains the second word.