iusmar
iusmar

Reputation: 359

How to select certain class in jQuery

Here's the problem; I have a couple of divs like the one below, same class name, no id. I need to modify the <span> text below the <h4> tag, based on where's the mouse cursor on those 3 images. I do this using javascript, by using mouseenter() method. The problem is that the method changes every span text from whole web page, not only from the class with class name "parent" where the mouse cursor is at the moment.

<div class="parent">
   <div class="parent.child">
      <a href="#"></a>
      <div class="parent.chil.child">
          <div class="parent.chil.child.child">
               <img src ="link1" data-price="a">
               <img src ="link2" data-price="b">
               <img src ="link3" data-price="c">
          </div>
      </div>
   </div>
   <h4>
      <a href= "aspPage.aspx">text</a>
   </h4>
   <p><span class = "spanClassName">text to be changed</span>some text</p>
   <div class=child1"></div>
</div>

How do I select only the link where's the mouse, from the curent "parent" div, even if there are several div with same class name, "parent".

I hope I was understood, if not, please ask and I try to explain more.

Upvotes: 0

Views: 73

Answers (2)

Satpal
Satpal

Reputation: 133403

You can use .closest() to find parent with .parent class

$('.parent\\.chil\\.child\\.child img').on('hover', function(){
    $(this).closest('.parent').find('.spanClassName').text($(this).attr('data-price'))
});

DEMO

Additionally as per documents you need to escape . in your selectors

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

Upvotes: 1

If you already know the specific parent node, just use parent.find('.spanClassName'). If you don't have the parent node, but you know which link the mouse is on, you can use link.closest('.parent').find('.spanClassName').

Upvotes: 0

Related Questions