Jessie Cui
Jessie Cui

Reputation: 25

Getting ID of a Neighbour Element in Javascript

I learned that you can get the parentElement of a srcElement that triggers a javascript function call using this:

    function selectThis() {
        var cbID = event.srcElement.id;
        var lblID = event.srcElement.parentElement.parentElement.id;
    }

where the elements are nested like this:

<asp:Label ID="lbl1" runat="server" >
    <asp:CheckBox ID="cb1" runat="server" onClick="selectThis()"/>
</asp:Label>
<asp:TextBox ID="txtbx1" runat="server" MaxLength="75"></asp:TextBox>

But is there a way to get the ID of the textbox below the label? Is there a "neighbourElement" type of thing?

Upvotes: 2

Views: 2395

Answers (3)

iamjpg
iamjpg

Reputation: 7628

I made a JSFiddle for you - using similar markup. https://jsfiddle.net/iamjpg/x1uqes9p/

var cb = document.querySelector('#checkbox1');

cb.onchange = function(e) {
    e.target.parentElement.nextElementSibling.value = "Woot"
}

In this example, when you check the checkbox it uses e.target.parentElement.nextElementSibling to set the value on the textarea.

Good luck.

Upvotes: 0

Brandon Pereira
Brandon Pereira

Reputation: 182

event.srcElement.parentElement.parentElement.nextElementSibling

You might need to add one more .parentElement (or 1 less) but that will return the element directly after the parent.

Upvotes: 2

Yonathanb
Yonathanb

Reputation: 57

If I understood you well try .NextSibling. BTW I would recommend you to use jquery for this kind of stuff

Upvotes: 1

Related Questions