0


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

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
praveenjayapal
  • 37,683
  • 30
  • 72
  • 72

2 Answers2

9

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Using `this` as a "context" is an alternative: `$("div").click(function(){ $("span", this).show(); });` – Phillip B Oldham Aug 25 '10 at 12:04
  • @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 Aug 25 '10 at 12:06
  • the source is like this!
    LinkCHECK
    The solution is good, but its not working here..
    – praveenjayapal Aug 25 '10 at 12:46
  • @praveenjayapal - I don't see a `
    ` in there...can you post everything relevant?
    – Nick Craver Aug 25 '10 at 12:51
  • Here the exact code,
    LinkCHECK
    $("legend").click(function(){ $(this).find("span").show(); }); Intially the span is hidden
    – praveenjayapal Aug 25 '10 at 12:57
  • @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 Aug 25 '10 at 13:02
  • yes, thanks Nick.. working good.. and also thanks for showing me a good stuff jsFiddle.. really nice.. – praveenjayapal Aug 25 '10 at 13:20
2

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

$("div").click(function(){      
    $(this).find("span").show();
});
tcooc
  • 20,629
  • 3
  • 39
  • 57