totalitarian
totalitarian

Reputation: 3666

Display text of just the element clicked

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

Answers (5)

michaelward82
michaelward82

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();
});

See this working fiddle

Upvotes: 1

chriz
chriz

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

Sudharsan S
Sudharsan S

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

Milind Anantwar
Milind Anantwar

Reputation: 82231

you need to use .find('span') to get child span:

$(this).find('span').show();

Working Demo

Upvotes: 2

Ankit Tyagi
Ankit Tyagi

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

Related Questions