2

I'm trying to use jQuery selector to access the DOM deep inside.

HTML

<table>
...more stuff here
  <tr>
    <td class="foo bar clickable">
      <div>
         <div class="number">111</div> //I want to get the value "111"
         <div class="content"></div>
      </div>
    </td>
    <td class="foo2 bar2 clickable">
      <div>
         <div class="number">222</div>
         <div class="content"></div>
      </div> 
    </td>
  </tr>
...more stuff here
</table>

So a user clicks on td and then I want to popup the alert with "111" shown.

In order to access <div class="number">111</div> part, I wrote the jQuery selector:

j$(".clickable").click(function() {

   //trying to output 111               
   alert( j$("this div div.number").text());
}

which returns blank alert box.

alert( j$("this div.number").text());

alert( j$("this div .number").text());

Tried few combination I can think of and all gave me blank alert. What am I doing wrong?

3 Answers 3

3

You don't have a <this> element anywhere so this div.number won't work. If you want to start at this and find the contained div.number, then you want to use .find like this:

j$(this).find('div.number').text()

Alternatively, you could use the context argument to jQuery:

j$('div.number', this).text()
Sign up to request clarification or add additional context in comments.

2 Comments

I guess I was using "this" in wrong way, now I'm clear, thank you!
@masato-san: Right, this is a JavaScript keyword that doesn't mean anything in a selector. You may have seen the j$('div.number', this).text() form of a jQuery call before but I prefer using .find as it is easier to tell what's going on at a glance.
2

Try this instead:

$(".clickable").click(function() {

   //trying to output 111               
   alert( $(this).find("div div.number").text());
});

I don't believe "this" in quotes has any meaning.

2 Comments

The "this" in the selector tells jQuery to look for a <this> element just like a "div" selector tells jQuery to look for a <div> element.
@mu right, I guess I didn't word that correctly. I meant more as a reference to current element, it doesn't work. If there were a <this> tag in the page then I guess it would match that.
0

try this code and practice with fiddler: http://jsfiddle.net/

You can paste in your HTML and your JS Code and simulate any Enviroment / Framework you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.