Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Hide all children, then show a specific element

I want to hide all child elements in a div. And then show a specific one passed on to the function.

function subDisplay(name) {    $("#navSub").each(function() {       $(this).hide();    });    $(name).show(); } 

then i call the function from an onmouse event like: subDisplay(#DivIwantToShow); But nothing displays...

What am i doing wrong?

like image 815
Christian Bekker Avatar asked Jan 05 '12 14:01

Christian Bekker


People also ask

How to show or hide a specified element using jQuery?

The toggle method. The toggle method of jQuery will hide specified visible element and display the hidden elements. Use toggle method if you need to allow users show or hide any elements like div, menu, paragraphs etc. in your web pages by giving a switchable option.

How to search through the children of a jQuery object?

Given a jQuery object that represents a set of DOM elements, the.children () method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements.

What is children () method in jQuery?

A string containing a selector expression to match elements against. Given a jQuery object that represents a set of DOM elements, the.children () method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements.

How to show/hide a circle with text using jQuery?

As you can see, I have created a circle with some text (basically for jQuery show / hide div example). When you click on the “show/hide” circle button, the toggle jQuery method will be called with three options.


2 Answers

You need to hide the children and not the containing div.

$("#navSub").children().hide();

So now if the div you are trying to show is an element in the parent div it will still show while the others stay hidden.

like image 160
Brandon Kindred Avatar answered Oct 16 '22 16:10

Brandon Kindred


If you're targeting the children of #navSub, you need target them and hide them, rather than the element navSub; which you can do using the children() method;

function subDisplay(name) {     $('#navSub').children().hide();     $(name).show(); }; 

Otherwise, it appears you have multiple elements with the same ID in your DOM, which is not allowed.

You then need to pass a string (which is a valid jQuery selector) to subDisplay();

subDisplay('#DivIwantToShow'); 
like image 38
Matt Avatar answered Oct 16 '22 15:10

Matt