uiatriot
uiatriot

Reputation: 45

Set div background color without using ID

Is possible change color of background my div using JavaScript without using ID? And how?

Html code is:

<div class="post" onmouseover="test(this)">

JS code is:

function test(item){
    alert("Hi :-)");   
}

Upvotes: 0

Views: 1163

Answers (2)

Steyn
Steyn

Reputation: 1321

Have you tried

function test(item){
  item.style.backgroundColor = "red";  
}

Since item is the actual div you're triggering this event on you won't need an ID to style the element.

A really easy (inline) solution would be the one below.

<div class="post" onmouseover="javascript:style.backgroundColor = 'red';">
    Content blabla
</div>

I would personally rather do all of this inside a JS file but hey this works too.

Upvotes: 4

Joshua Belden
Joshua Belden

Reputation: 10503

You can loop through the DOM with JavaScript, but you'll have a better time of it if you're using JQuery. You'll want to invest some time learning about selectors:

You'll be looking for something like:

function test(){
   var element = $('div');
}

As people have shared in the comments, without a unique identifier, you'll have a rough time, especially as new elements are added to the page.

Upvotes: 1

Related Questions