thadeuszlay thadeuszlay - 1 year ago 78
Javascript Question

How to get current element in order to select with javascript?

I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):

<div class="classA">
<select onchange="updateInputBox()">
<div class="classB">
<input data-myAttribute="case1">
<div class="classC">
<a type="button">
<i class="fa fa-remove">x</i>

The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.

Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):

But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?

I tried to pass itself in the updateInputBox-function:

<select id="selectBox" onchange="updateInputBox('+ this +')">

I also tried with jQuery:


but in both cases the console would say

"Unexpected identifier"

Inside the function doing something like this (currentElement is the selectBox/DropDownBox):

currentElement.parent().parent().setAttribute("data-myAttribute", "hello");

Uncaught TypeError: selectBox.parent is not a function

Answer Source

You can use jquery 'closest' for this as below.


<select id="selectBox" onchange="updateInputBox(this)">


function updateInputBox(selectElm) {
   var inputElm = $(selectElm).closest('fieldset').find('input');

inputElm.attr('data-myAttribute', $(selectElm).val());


// instead of inline onchange event and the above code, you can use the below to trigger the event

$(document).on('change', 'fieldset select', function () {
       var inputElm = $(this).closest('fieldset').find('input');

    inputElm.attr('data-myAttribute', $(this).val());

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download