views:

72

answers:

2

Hi friends,
I need to access a SPAN tag with in every DIV tag
so i used this following code

    $("DIV").click(function(){      
    $(this + "SPAN").show();
});


Is the above code is correct? Its not working for me! Its showing nothing too..
Please help me


Thanks,
Praveen J

+9  A: 

You can use .find() for getting an element inside another, like this:

$("div").click(function(){      
  $(this).find("span").show();
});

As a general rule, to get anything relative to this, you're typically going to start with $(this) and some combination of the tree traversal functions to move around.


For actual code, based on comments below:
If your code looks like this:

<fieldset>
  <legend>Link</legend>
  <span>CHECK</span>
</fieldset> 

Then .find() won't work since on $("legend") selector because the <span> isn't inside the <legend> it's a sibling, so use .siblings() (optionally with a selector) like this:

$("legend").click(function(){ 
  $(this).siblings("span").show(); 
});​

You can give it a try here

Nick Craver
Using `this` as a "context" is an alternative: `$("div").click(function(){ $("span", this).show(); });`
digitala
@digitala - It's converted to the same `.find()` call :) Just many more steps to get there, including 2 regexes :) ....you can take a look at the source here: http://github.com/jquery/jquery/blob/master/src/core.js#L153
Nick Craver
the source is like this! <fieldset><legend>Link</legend><span>CHECK</span></fieldset>The solution is good, but its not working here..
praveenjayapal
@praveenjayapal - I don't see a `<div>` in there...can you post everything relevant?
Nick Craver
Here the exact code,<fieldset><legend>Link</legend><span>CHECK</span></fieldset>$("legend").click(function(){$(this).find("span").show();});Intially the span is hidden
praveenjayapal
@praveenjayapal - Ah, you need `.siblings()` rather than `.find()`, since it's not *in* the element, like this: `$("legend").click(function(){ $(this).siblings("span").show(); });​` [you can give it a try here](http://jsfiddle.net/nick_craver/2Bxem/)
Nick Craver
yes, thanks Nick.. working good.. and also thanks for showing me a good stuff jsFiddle.. really nice..
praveenjayapal
+2  A: 

You can use the find function to do that. (Also, using lowercase for selectors is preferred.)

$("div").click(function(){      
    $(this).find("span").show();
});
digitalFresh