html - How to only show elements of a class that I clicked while hiding everything else with jQuery? -


beginner here, tried best around didn't find same.

i have situation have multiple appearances of same 4 types of links (each own class).

ex:

<a href="#" class="link1">link 1</a> <a href="#" class="link2">link 2</a> <a href="#" class="link3">link 3</a> <a href="#" class="link4">link 4</a> <a href="#" class="link1">link 1</a> <a href="#" class="link2">link 2</a> <a href="#" class="link3">link 3</a> <a href="#" class="link4">link 4</a> 

i trying if click 'link 1', links classes 2-4 disappear (off page) , links class, "link1" show.

<a href="#" class="link1">link 1</a> <a href="#" class="link1">link 1</a>` 

i have tried creating assigning clicked link variable , using .not() or .siblings(), far can't work.

var clickedlink = $(this).closest('a').attr('class'); $(clickedlink).siblings().hide(); 

also tried giving of links shared class (such class="test, link1") .hide() , .show(), hide() , not show().

thanks ton @ all.

the following, simplified, example should on way:

https://jsfiddle.net/jhqbf4nb/

$('.wrap a').click(function() {   var $target = $(this);    $target.siblings().not('.' + $target.attr('class')).hide(); }) 

note added wrapper .wrap around links make selection bit easier.


in fact, above solution bit simple liking. should work in case, make lot of assumptions dom structure. in real life go in order:

https://jsfiddle.net/jhqbf4nb/1/

var $links = $('.link');  $links.click(function() {   var $target = $(this);   var type = $target.data('type');    $links.not('[data-type="' + type + '"]').hide(); }) 

i moved 'type' data-type attribute. way can have many classes on links. also, not have siblings anymore, can anywhere in dom. should lot more flexible, , keep better when dom changes in future (and believe easier understand when first read well, , i'm big fan of self explaining code).


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -