javascript - How can I target an element's 'parent' - Stack Overflow

I have some <TD>s without unique names. Inside them there are spans with unique classnames so I h

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".

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".

Share Improve this question edited Apr 19, 2011 at 14:42 David Tang 93.7k32 gold badges168 silver badges149 bronze badges asked Apr 19, 2011 at 14:30 124697124697 21.9k69 gold badges197 silver badges319 bronze badges 1
  • 1 You can use .find('.newClass'); – Khez Commented Apr 19, 2011 at 14:31
Add a ment  | 

5 Answers 5

Reset to default 6

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 remend using the jQuery function addClass() anyway since it won't interfere with existing classes.

You can do

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

Sorry, do you mean following code:

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745299634a4621356.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信