views:

169

answers:

2

Hey all,

I'm practicing Jquery and I've written this simple Jquery statement:

var someText = $("table tr td").text();

Should this not return all text of td elements found within tr's that are found within tables? How do I fix this? Currently when I run this, it says that table tr td is null, but I have a table on the page I'm testing on.

Thanks!

+2  A: 

Alex,

nvl corrected me on text() - confused its functionality with html() for a minute, so what you have likely should be returning something.

Try wrapping your code in this:

$(document).ready(function() {
    // Your code here
});

If you don't do this, you're probably getting back a null response because the browser doesn't actually have any HTML content yet to perform your function on!

Details here: http://www.learningjquery.com/2006/09/introducing-document-ready

Sample working HTML doc using this:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
  $(document).ready(function() {
      var someText = $("table tr td").text();
      alert(someText);
  });

</script>
</head>
<body>
    <table>
        <tr>
            <td>help</td>
            <td>me</td>
        </tr>
    </table>
</body>
</html>

Does indeed output 'helpme' in an alert box.

AvatarKava
can I do something like `var myText = $("table tr td").each().text();`?
Alex
Sorry nvl, bit late and confused html() and text() functionality :)
AvatarKava
Yes I believe so, lemme double check.
Alex
Nope I did not, but it is still returning null, lemme revise my selector.
Alex
+2  A: 

From jQuery,

.text()
Get the combined text contents of each element in the set of matched elements, including their descendants.

I have tested it and it indeed returns concatenated text of the elements matched.


<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">Admission</a></li>
  <li><a href="#">Courses</a></li>
  <li><a href="#">Faculty</a></li>
  <li><a href="#">Research</a></li>
  <li><a href="#">Contact</a></li>
</ul>

Applying .text() on above html,

alert( $("ul li").text() );  

"HomeAdmissionCoursesFacultyResearchContact"

N 1.1
I'm a Jquery beginner, so could you maybe give me an example of how you would use this? This is much appreciated.
Alex
@Alex: i included an example. Try to apply on your page now.
N 1.1