CLiown
CLiown

Reputation: 13843

jQuery - Traversing the DOM

Here is my HTML:

                    <li>
                        <div class="menu_inner">
                            <a href="#">
                                <div class="button"><img class="486" src="images/portalbutton.png" /></div>
                                <div class="prod_description">&nbsp;</div>
                            </a>
                        </div>
                    </li>

I want to add a .click() function to .prod_description, the click event should take the background colour applied in CSS from the li element.

Using this code:

$(".prod_description").mousedown(function() {
    $('#toolbar').css('background-color', $(this).parent().css('background-color'))
})

I dont seem to be able to get the correct $(this).parent() combination....

Upvotes: 0

Views: 133

Answers (3)

jholster
jholster

Reputation: 5136

In javascript, you must use backgroundColor, not background-color.

Update: As it turns out, jQuery is able to handle both formats, and even the DOM API itself let you do something like this: obj.style.setProperty('background-color', 'red');

Upvotes: 1

rahul
rahul

Reputation: 187030

Use click event instead of mousedown. Use closest to get the li element

$("div.prod_description").click(function() {
    $('#toolbar').css('background-color', $(this).closest('li').css('background-color'))
});

I have used a tag selector also in the click event. If you can give the background color in a CSS class, then you can use something like this

li.mybg { background-color: #a9a9a9; }

<li class="mybg">
   <div class="menu_inner">
      <a href="#">
         <div class="button">
             <img class="486" src="images/portalbutton.png" />
         </div>
         <div class="prod_description">&nbsp;</div>
      </a>
   </div>
 </li>

$("div.prod_description").click(function() {
    $('#toolbar').addClass('mybg');
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

You can do that like this:

$(".prod_description").mousedown(function() {
    $('#toolbar').css('background-color', $(this).closest('li').css('background-color'))
});

.parent() gets the immediate parent, you want to go up a few levels (<a>, <div>, <li>). .closest('li') climbs the parents and gets the first one that's an <li>. In this case, .parent('li') would also work :)

Upvotes: 3

Related Questions