[Solved] Use a span tag to change div background-color onclick [closed]


Using vanilla JavaScript (no libraries):

//We attach a click handler on the nearest common parent.
//This allows us to have only one event handler, which is better
//For performance!
document.getElementById("parent").onclick = function(e) {
    //We only want events on the spans, so let's check that!
    if (e.target.tagName.toLowerCase() == "span") { 
        this.style.backgroundColor = "#BADA55";
        //This is for the sake of example only!
        //TODO: A better approach would be to add a class
        //And define a CSS rule for that class.
    }
};

Or without the comments

document.getElementById("parent").onclick = function(e) {
    if (e.target.tagname.toLowerCase() == "span") { 
        this.style.backgroundColor = "#BADA55";
    }
};

The equivalent of the above with jQuery:

$("#parent").on("span", "click", function() {
    $("#parent").css({backgroundColor: "#BADA55"});
});

Example

solved Use a span tag to change div background-color onclick [closed]