0
<table border=0>
  <tr>
    <td>
      <table  id="table1" width="300" border="2" align="right" cellpadding="1" cellspacing="1">
          <tr class="tb1">
          <td>station</td>
          <td>wind</td>
          </tr>
      </table>
    </td>
  </tr>
</table>

I hope to return the value of element through javascript which I expect to alert with the string "station" and "wind". I had tried the following javascript code

var data=$("tr.tb1").find("td").value;
alert(data);

And further more to change the font color of the content. Hoping to get some help about how to improve my code.

lu555
  • 43
  • 1
  • 7

5 Answers5

1

You can use .text() to get the text content of a dom element

.val() works on input elements and .text() will not work on input elements. more here

var data=$("tr.tb1").find("td").text();
alert(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=0>
  <tr>
    <td>
      <table  id="table1" width="300" border="2" align="right" cellpadding="1" cellspacing="1">
          <tr class="tb1">
          <td>station</td>
          <td>wind</td>
          </tr>
      </table>
    </td>
  </tr>
</table>
Tareq
  • 5,283
  • 2
  • 15
  • 18
0

Try this

$('.tb1').find("td").each(function()
{
   alert($(this).html());
});
Sowdhanya
  • 63
  • 4
0

.find()

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

You can use each() to get all td's returned by .find(). There is no value attribute in td, you can use textContent instead. Try the following:

$(".tb1").find("td").each(function(){ 
  var data = this.textContent;
  alert(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=0>
  <tr>
    <td>
      <table  id="table1" width="300" border="2" align="right" cellpadding="1" cellspacing="1">
          <tr class="tb1">
            <td>station</td>
            <td>wind</td>
          </tr>
      </table>
    </td>
  </tr>
</table>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You can use Document.querySelectorAll() and Function.prototype.call(): Array.prototype.map() and Array.prototype.join().

Code:

const elems = document.querySelectorAll('tr.tb1 td');
const result = Array.prototype.map.call(elems, el => el.innerHTML).join(' ');

alert(result);
<table border=0>
  <tr>
    <td>
      <table  id="table1" width="300" border="2" align="right" cellpadding="1" cellspacing="1">
          <tr class="tb1">
            <td>station</td>
            <td>wind</td>
          </tr>
      </table>
    </td>
  </tr>
</table>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

You can use jquery text method .text(); or .html() like this:

var data=$("#table1 .tb1").find("td");

alert(data.html());
alert(data.text());

And for css styling

data.css({"color": "blue"});
4b0
  • 21,981
  • 30
  • 95
  • 142