How to get element inside element by id and class using plain JavaScript


If you have multiple elements with same class name in your html page and you want to select particular element using its class, sometimes it may become difficult to select the element we want.

For example: I have two <select> with same class name "myclass1". Now I want to get the selected option in the second <select>.



<div id="mydiv1">
    <select class="myclass1">
        <option>Opt 1.1</option>
        <option>Opt 1.2</option>
        <option selected>Opt 1.3</option>
    </select>
</div>
<div id="mydiv2">
    <select class="myclass1">
        <option>Opt 2.1</option>
        <option selected>Opt 2.2</option>
        <option>Opt 2.3</option>
    </select>
</div>
I want to get the selected value in second <select> which is inside second div "mydiv2".


Below simple plain java script will do this job;
var selected=document.getElementById("mydiv2").getElementsByClassName("myClass1")[0];
alert(selected.options[selected.selectedIndex].value);

getElementById returns the the node "mydiv2". Now getElementsByClassName returns all the nodes inside "mydiv2" with class name "myclass1". So getElementsByClassName("myClass1")[0] will give the <select> element. Now selected.options[selected.selectedIndex].value will give us the selected value.




Complete example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Hello App</title>
    <script type="text/javascript">
    function selectElement(){
       var selected=document.getElementById("mydiv2").getElementsByClassName("myClass1")[0];
       alert(selected.options[selected.selectedIndex].value)
}
    </script>
  </head>
 
  <body>
    <h1>Hello App!</h1>
    <div>
        <div id="mydiv1">
            <select class="myclass1">
                <option>Opt 1.1</option>
                <option>Opt 1.2</option>
                <option selected>Opt 1.3</option>
            </select>
        </div>
        <div id="mydiv2">
            <select class="myclass1">
                <option>Opt 2.1</option>
                <option selected>Opt 2.2</option>
                <option>Opt 2.3</option>
            </select>
        </div>
        <button onclick="selectElement()">Select Element</button>
    </div>
  </body>
</html>




Reactions:

0 comments :

Post a Comment