SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Jan 2009
    Posts
    353
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to address 'this' ?

    How to address 'this' ?

    Hi all

    I have a simple example to illustrate my problem here.

    http://www.ttmt.org.uk/this/

    I have a group of div's with a <p> tag inside.

    When I click the div I want to place text in the <p> of that button.

    How do I address the <p> of this div being clicked.

    I tried this.

    Code:
    <script type="text/javascript">
      $('div').click(function(){
        $(this).$('p').html('BTN');
      });
    </script>
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    
    	<title>untitled</title>
      
    	<style type="text/css" media="screen">
    	 *{
    	   margin:0;
    	   padding:0;
    	 }
    	 div.btn{
    	   background:red;
    	   cursor:pointer;
    	   height:100px;
    	   margin:50px;
    	   width:200px;
    	 }
    	</style>
    </head>
    
    <body>
    
      <div class="btn">
        <p></p>
      </div>
      
      <div class="btn">
        <p></p>
      </div>
      
      <div class="btn">
        <p></p>
      </div>
      
      <div class="btn">
        <p></p>
      </div>
      
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
      
      <script type="text/javascript">
        $('div').click(function(){
          $(this).$('p').html('BTN');
        });
      </script>
    	
    </body>
    </html>

  2. #2
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    UK
    Posts
    163
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'n no expert, but isn't it something like
    $(this).children('p')
    to access the p descendants of $this ?

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,526
    Mentioned
    83 Post(s)
    Tagged
    4 Thread(s)
    You use the p selector from within the context of the this element. See http://api.jquery.com/jQuery/#jQuery1

    Code javascript:
    $('p', this).html('BTN');
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •