Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with changing child div style using jQuery (via class selector)

Tags:

html

jquery

css

this is more curiosity question rather than a problem)

With my Rails 3 application I generate a lots of blocks, which contain div elements. One block looks like this:

<div class="link_div">
        <%= link_to ... %>
        <div class="ranking">
        <%= link_to ... %>
        <%= link_to ... %>
        <%= link_to ... %>
    </div>
</div>

And now Im trying to toggle "ranking" div visibility on mouseOVER. It wasnt so easy, cause I`m a newbie to jQuery. I was trying a lots of css accessors, but finnally I have found a solution look like this:

$('.link_div').hover(
      function () {
        $(this).children('.ranking').css('display','block');
      },
      function () {
        $(this).children('.ranking').css('display','none');
      }
);

So the question is: "Why this solution doesn`t work?":

$(this).children()[1].css('display','block');

Alert says that chilren()[1] gives me div object, but it doesn`t have .css() method. Why?

alert($(this).children()[1]) // => "[object HTMLDivElement]"
like image 759
makaroni4 Avatar asked Dec 20 '25 21:12

makaroni4


2 Answers

Why are you doing this in javascript? This is clearly something that belongs in css. You will get a lot clearer code, A better separation between markup, content and behavior and a huge performance gain.

example

like image 128
Jan Avatar answered Dec 22 '25 11:12

Jan


Here is a demo of a very simple way of showing/hiding the ranking <div> when hovering over the <div class="link_div">

The selector $('.ranking', this) matches all elements with class .ranking inside the current element (the context) and applies the show() function to them.

As others have already answered, your problem is that you have dereferenced the jQuery object with the [1] and you have a raw DOM object. You need to call functions on the jQuery objects in this case.

like image 31
andyb Avatar answered Dec 22 '25 11:12

andyb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!