Reputation: 3666
I need to be able to click on a div, show the text within it, then when clicking on another div, hide all the other text in other divs and show the text in the clicked div.
Code here
http://jsfiddle.net/Refxq/140/
<div class="myClass"><span>First</span></div>
<div class="myClass"><span>Second</span></div>
<div class="myClass"><span>Third</span></div>
.myClass{
height:50px;
width:100%;
background-color:red;
margin:2px;
}
.myClass span{
display:none;
}
$(".myClass").click(function() {
// Hide all item spans
$(".myClass span").hide();
// Show the element next to this
$(this).first().show();
});
Upvotes: 2
Views: 56
Reputation: 4736
Use jQuery's not() function to exclude the item you wish to show from the hiding process.
$(".myClass").on('click', function () {
// Store a reference to the element we want to show
var shownElement = $(this).find('span');
// Ensure 'shownElement' is shown
shownElement.show();
// Hide everything apart from 'shownElement'
$(".myClass span").not(shownElement).hide();
});
Upvotes: 1
Reputation: 1345
You mean accordion.. just have a look at this jquery plugin. its easy..
or if thruegh code..
$(".myClass").click(function() {
$(".myClass span").css('display','none');
$(this).find('span').css('display','block');
});
Upvotes: 0
Reputation: 15393
use .find in Jquery; the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements.
$(this).find('span').show();
or .has() in jquery Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
$(this).has('span').show();
Upvotes: 2
Reputation: 82231
you need to use .find('span')
to get child span:
$(this).find('span').show();
Upvotes: 2
Reputation: 2375
This will work : See fiddle
$(".myClass").click(function() {
// Hide all item spans
$(".myClass span").hide();
// Show the element next to this
$(this).find('span').show();
});
Upvotes: 3