jQuery - Changing the color of a specific table element

I have this table:

<table border=1 id="Table">
<tr> <th> Product </th> <th> Price </th> <th> Shop </th> </tr>
<tr> <td> Stuff1 </td> <td> 10$ </td> <td> Shop1 </td></tr>
<tr> <td> Stuff2 </td> <td> 0$ </td> <td> Shop2 </td></tr>
</table>

On which I try using the following jQuery code:

var cell = $("#Table").find("td")[4];
cell.css("background-color", "red");

$("#Table").find("td")[4].innerHTML gives me Stuff2. But I can't seem to change the css at all with jQuery or even use html().

Answers


This:

var cell = $("#Table").find("td")[4];

gives you the DOM element at index 4 so it only has native DOM methods.

Change it to this to call jQuery methods:

var cell = $("#Table").find("td").eq(4);

or this:

var cell = $("#Table td").eq(4);

Using [] extracts the DOM element so you cannot use .css() jquery method on it afterwards.

Use a selector:

var $cell = $("#Table").find("td:eq(4)"); // or $("#Table").find("td").eq(4);
$cell.css("background-color", "red");

Note: by convention, jquery variables should prefixed with $(like $cell) so they are easily as such.


When using the array-notation you get no longer a jQuery-object, but the plain dom-node. What you need here is the :eq selector:

var cell = $("#Table").find("td:eq(4)");
cell.css("background-color", "red");

cf. http://api.jquery.com/eq-selector/


Need Your Help

Best Database for this, NOSQL vs MySQL

mysql database nosql

I have an App based around Events and Branches. I have two events ones with Branches and ones Without.

javascript initialize to undefined or null or “”

javascript undefined

Java script has many falsy values as I started learning. I have a program that gets values from a service and loads into an array like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.