开发者

get sibling that has id

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


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.


Recursively iterate through the parent div and add logic to separate the inputs that have IDs


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
}   

}


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
}


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}]`)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜