get the next element with a specific class after a specific element

Viewed 31440

I have a HTML markup like this:

<p>
  <label>Arrive</label>
  <input id="from-date1" class="from-date calender" type="text" />
</p>

<p>
  <label>Depart</label>
  <input id="to-date1" class="to-date calender" type="text" />
</p>

<p>
  <label>Arrive</label>
  <input id="from-date2" class="from-date calender" type="text" />
</p>

<p>
  <label>Depart</label>
  <input id="to-date2" class="to-date calender" type="text" />
</p>

I want to get the next element after from dates to get the corresponding to date. (Layout is a little more complex but from date has from-date class and to date has to-date class).

This is I am trying to do, I want to take a from date element and find the next element in the dom with to-date class. I tried this:

$('#from-date1').next('.to-date')

but it is giving me empty jQuery element. I think this is because next gives the next sibling matching the selector. How can I get the corresponding to-date?

5 Answers
    var item_html = document.getElementById('from-date1');
    var str_number = item_html.attributes.getNamedItem("id").value;
    // Get id's value.
    var data_number = showIntFromString(str_number);


    // Get to-date this class
    // Select by JQ. $('.to-date'+data_number)
    console.log('to-date'+data_number);

    function showIntFromString(text){
       var num_g = text.match(/\d+/);
       if(num_g != null){
          console.log("Your number:"+num_g[0]);
          var num = num_g[0];
          return num;
       }else{
          return;
       }
    }

Use JS. to get the key number from your id. Analysis it than output the number. Use JQ. selecter combine string with you want than + this number. Hope this can help you too.

I know this is an old question, but I figured I'd add a jQuery free alternate solution :)

I tried to keep the code simple by avoiding traversing the DOM.

let inputArray = document.querySelectorAll(".calender");

function nextInput(currentInput, inputClass) {
    for (i = 0; i < inputArray.length - 1; i++) {
        if(currentInput == inputArray[i]) {
            for (j = 1; j < inputArray.length - i; j++) {
                //Check if the next element exists and if it has the desired class
                if(inputArray[i + j] && (inputArray[i + j].className == inputClass)) {
                    return inputArray[i + j];
                    break;
                }
            }
        }
    }   
}

let currentInput = document.getElementById('from-date1');

console.log(nextInput(currentInput, 'to-date calender'));

If you know that the to date will always be the next input element with a class of "calender", then you don't need the second loop.

Related