124697
124697

Reputation: 21901

How can I target an element's 'parent'

I have some <TD>s without unique names. Inside them there are spans with unique classnames so I have no problem targetting the spans. How can I target the parent <td> so I can change its class?

I want to do something like $(".classname").parent("TD").className="newClassclassname".

Upvotes: 1

Views: 1224

Answers (5)

Alex
Alex

Reputation: 7374

$(".classname").parent().addClass("newClassclassname");

Upvotes: 0

Sean Adkinson
Sean Adkinson

Reputation: 8615

$(".classname").parent("TD")[0].className="newClassname";

Upvotes: 1

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9983

Sorry, do you mean following code:

$(".classname").parent("TD").addClass("newClassName");

Upvotes: 1

Sang Suantak
Sang Suantak

Reputation: 5265

You can do

$("span.classname").closest("td").addClass("newClassclassname");

Upvotes: 2

David Tang
David Tang

Reputation: 93694

You were close:

 $('.classname').parent('td').addClass('newClassName');

Though typically it's safer to go with:

 $('.classname').closest('td').addClass('newClassName');

... which doesn't assume the <td> is the immediate parent.


The reason .className doesn't work is because jQuery returns elements wrapped in the jQuery object. If you want to access the original (DOM) object you need to select the first item in the jQuery collection with [0]:

 $('.classname').parent('td')[0].className = 'newClassName';

But I recommend using the jQuery function addClass() anyway since it won't interfere with existing classes.

Upvotes: 6

Related Questions