Reputation: 8246
So I have the following structure:
<div id="some id">
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
<div>
<input id="some other id" ....>
.....bunch of other inputs with no id field....
<select onclick="findSiblingWithId()">
</div>
So in my findSiblingWithId i don't know the id I'm looking for, all I know is that for the other components in the same div, only one will have an id. How can I get that ?
Edit:
Since it seems I didnt explain well enough I'll try to add more info. So I want for example when the select component changes (here it could be a button or anything, it doesnt matter) to get the corresponding <input id="some other id" ..>
from the same div.
Like I tried to explain above, I have one huge div, the <div id="some id">
, now this contains a number of smaller <div>
without ids.
Each of these smaller divs will have ONE inputfield with an ID and a bunch of other without an ID. Now on an action, doesn't matter if a button click or whatever, from a component located IN THE SAME div (I thought the correct work would be 'sibling') is there a way I can find the input that has an ID attribute?
Regards, Bogdan
Upvotes: 1
Views: 7509
Reputation: 320
The most direct way to get the value that has this id among the siblings is to use the sibling's filter like this:
let my_id = ...
$(this).siblings(`div[id=${my_id}]`)
Upvotes: 1
Reputation: 816910
You could iterate over all children of the parent:
function findSiblingWithId(element) {
var siblings = element.parentNode.children,
sibWithId = null;
for(var i = siblings.length; i--;) {
if(siblings[i].id) {
sibWithId = siblings[i];
break;
}
}
if(sibWithId) [
// found it
}
};
You have to pass the clicked element (I hope you have a proper select
field);
<select onclick="findSiblingWithId(this)">
Consider to attach the event handler for the change
event, if you want to have it triggered when the user selected a value.
Upvotes: 4
Reputation: 26951
Using jQuery:
<!--Modify HTML so input is -->
<select onclick="findSiblingWithId(this)">
findSiblingWithId(elem){
return $(elem).siblings("[id]"); //if you need all
//return $(elem).siblings("[id]:eq(0)"); //if you need only first
}
Upvotes: 0
Reputation: 474
function findSiblingWithId(element) {
var sibling = null;
if (element.parentNode != null) {
sibling = element.parentNode.nextSibling;
// Then go through the child elements of your sibling node and get the one with an id
}
}
Upvotes: 0
Reputation: 46067
Recursively iterate through the parent div and add logic to separate the inputs that have IDs
Upvotes: 0