How to select only one DIV from multiple divs using javascript

Tags: , ,

I have below code in my HTML which has multiple DIV’s, I would like to use these DIV’s as options. For this reason, the DIV which is being clicked should be selectable (leaving others non selected – only one should be active) and when I click on Confirm link, the value within the selected DIV should be displayed on message box.

<div style="margin-top:10px;">
    <div class="optionsecoptions">
    <div class="optionsecoptions" style="top:151px;">
    <div class="optionsecoptions" style="top:212px;">
    <div class="optionsecoptions" style="top:273px;">
<a href="#"> Confirm </a>

Here is the demo :

I tried some solution in Jquery, but is this possible using simple javascript ? please help!


You may use addEventListener for a javascript only solution to add/remove a particular class from your <div>.

You would need to iterate over all elements with class .optionsecoptions and attach click event listener on each of them, (or better enclose all <div> in a wrapper and exploit bubbling of click event)

var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function(){

    var selectedEl = document.querySelector(".selected");

    }, false);;

Here’s the workingdemo

Source: stackoverflow