Mjukis Mjukis - 10 days ago 4
Javascript Question

Jquery traversing. Find siblings including it self

I'm using Jquery traversing to jump between DOM elements.


First of i have a onClick function:

$(document).on('keyup', '.size, .ant', function(){


Inside of this function i send data about what's clicked, to another function..

sulorTableRowWeight( $(this) );


function sulorTableRowWeight(thisobj){


Now, i'd like to traverse from clicked element
$(this)
to it´s parent. I'd like to find the parents siblings and then traverse down to a specific sibling.

var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size');


My problem is when i'd like to travers back down to the element i came from.
it is not listed as a sibling because it isn't a sibling...


var inputSize = $(thisobj).parent().siblings(); console.log(inputSize)

console will give me the siblings.. but not the one i came from...

So, when a user click ".size" i'd like to travers up to parents and back to size.... When a user click ".ant" i'd like to traverse up to parents and then down to ".size"..

I tried to hardcode the traversing:

var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size');


But it wont work.. because it is not actual a sibling..

So what is it? and how can i get back to it?

If it is not possible, i have to run some if/else statements... i guess..

UPDATE


$(document).on('keyup', '.size, .ant', function(){
//Find changed <select> .tbody
var tbodyId = $(this).parent().parent('tr').parent('tbody').attr('id');
//Check <tbody> #id
if(tbodyId === "cpTableBody"){
}
else if(tbodyId === "sulorTableBody"){
sulorTableRowWeight( $(this) );
}
else if(tbodyId === "konturTableBody"){
konturTableRowWeight( $(this) );
}
else if(tbodyId === "kantbalkTableBody"){
kantbalkTableRowWeight( $(this) );
}
})

//Function sulorTableRowWeight
function sulorTableRowWeight(thisobj){

//Find the selected data-weight
var selectedWeightmm3 = $(thisobj).parent().siblings('.selectTd').children('.select').find(':selected').data('weightmm3');

//Find input .size value
var inputSize = $(thisobj).parent().siblings('.sizeTd').children('.size'); console.log(inputSize)


PROBLEM

My var
inputSize
will return undefined when i click a ".size" element.
That´s because it is not listed as a sibling to it self.

I know.. it´s keyup.. not click...

Answer

e.target will select the current input

$(document).on('keyup', '.size, .ant', function(e) {
  inputSize = $(e.target);
  if($(e.target).is('.ant')) {//test if the element is .ant 
  inputSize = $(e.target).parent().find('.size');//get .size based on .ant
  }
   console.log(inputSize[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <input class="size x1" placeholder="x1">
  <input class="ant x1" placeholder="x1 ant">
</div>
<div>
  <input class="size x2" placeholder="x2">
  <input class="ant x2" placeholder="x2 ant">
</div>

Comments