Skip to content
Advertisement

How to select only one DIV from multiple divs using javascript

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">
        &nbsp;&nbsp;Computers
    </div>
    <div class="optionsecoptions" style="top:151px;">
        &nbsp;&nbsp;Electronics
    </div>
    <div class="optionsecoptions" style="top:212px;">
        &nbsp;&nbsp;Mechanical
    </div>
    <div class="optionsecoptions" style="top:273px;">
        &nbsp;&nbsp;Electrical
    </div>
</div>
<a href="#"> Confirm </a>

Here is the demo :

http://jsfiddle.net/sathish_opr/ntxuc69a/

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

Advertisement

Answer

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");
    if(selectedEl){
        selectedEl.classList.remove("selected");
    }
    this.classList.add("selected");

    }, false);;
}

Here’s the workingdemo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement