is there a way to target a specific div using jquery, even though there are more identical divs?

StackOverflow https://stackoverflow.com/questions/22925314

  •  29-06-2023
  •  | 
  •  

سؤال

I made an example here http://jsfiddle.net/nLybj/108/

When you mouseover .test I don't want to affect all, only the closest .lol and make it disappear.

I managed to do this using .next() but if I have more divs in between test and lol I have to keep adding more .next() into the code.

I was wondering if there was a another way of doing this that would be much cleaner?

هل كانت مفيدة؟

المحلول

I updated your JsFiddle to work with as many elements you want ! Basically only select the next element with the .lol class using jQuery nextAll() function, then take the first of the next.

Example : http://jsfiddle.net/nLybj/115/

$(this).nextAll('.lol:first')

نصائح أخرى

Wrap divs in between hrs and then use $(this).parent().children('div[class="test"] ~ div[class="lol"]') to select all the .lol divs:

<div>
    <div class="test">test</div>
    <div class="sdf">sdf</div>
    <div class="lol">lol</div> 
</div>
<hr>
<div>
    <div class="test">test</div>
    <div class="sdf">sdf</div>
    <div class="else">else</div> 
    <div class="lol">lol</div> 
</div> 
<hr>
<div>
    <div class="test">test</div>
    <div class="sdf">sdf</div>
    <div class="lol">lol</div> 
</div>

$(document).ready(function(){
    $(".test").on({
        mouseover: function(){
            $(this).parent().children('div[class="test"] ~ div[class="lol"]').addClass('hide');
        },
        mouseout: function(){
            $(this).parent().children('div[class="test"] ~ div[class="lol"]').removeClass('hide');
        }
    });
});

I would wrap your elements in a container, and then search only the container for an element with the lol class:

Take a look at this http://jsfiddle.net/nLybj/109/

(this).parent().find('.lol').addClass('hide');

Why not use CSS? It's faster, and less overhead than trying to affect the view using Javascript/jQuery.

.test:hover + div + .lol {
    display: none;
}

Updated your JSFiddle

Updated your JSFiddle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top