zall
zall

Reputation: 585

How to change the background of a specific div when clicked

Note: I don't know jQuery so please don't give me an answer how how to do it using jQuery.

I have multiple divs. I want to know how I could access it and change its specific color when clicked using JavaScript.

I am not looking for a solution like document.getElementsByTagName("div")[0] because it requires inputting a seperate number for each div.

I was hoping there was a simple solution somewhat like this.

<div onClick="change();"><h1>Hi</h1><div>
<div onClick="change();"><h1>Hi</h1><div>       
<div onClick="change();"><h1>Hi</h1><div>   

<script>
        function change(){
            this.style.backgroundColor = "red";
        }
</script>

Upvotes: 1

Views: 622

Answers (2)

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

This would be more easy.

<div onclick="changeColor(this)">Some text!</div>
<p>A paragraph, that will have no change by click</p>

For JavaScript write this:

function changeColor(div) {
  div.style.backgroundColor = #hexvalue
}

This will change the background color of the div and not the <p>. You can set any css value for any element by using this jQuery code.

However, for me the jQuery was pretty easy! :) But as you wish.

Upvotes: 0

user2246674
user2246674

Reputation: 7719

Since you don't want to learn jQuery (or presumably, non-inline events), consider:

<div onclick="change(this)"><h1>Hi Dave!</h1></div>   <!-- use closing tags -->
<div onclick="change(this)"><h1>Hi Thomas!</h1></div>   

function change(elm) {
    elm.style.backgroundColor = 'red'
}

Note that the context (this) of the inline event handler code (as specified in the attribute) is the element which was the target of the event - for this case it will be the specific DIV element that was clicked. We then simply pass the element into the callback function so we can use it generically.

Also, in the initial markup, the div elements were not closed and led to nesting. With the corrections, the above approach works to complete the task. (The fiddle code assigns to window.change directly, but it's otherwise the same concept.)


Of course, learning jQuery (or a different) high-level framework will probably pay off quite quickly. Using inline event-handlers is .. very "old school".

Upvotes: 2

Related Questions