将类添加到HTML元素

时间:2014-04-03 18:56:12

标签: javascript jquery

我希望将<li>元素添加到<a href="http://localhost/hello/5">元素。

我试试,但它不起作用:

$("<li><a>[href|='http://localhost/hello/5']").addClass( "active" );

2 个答案:

答案 0 :(得分:2)

要添加到父<li>

$("[href='http://localhost/hello/5']").parent("li").addClass( "active" );

答案 1 :(得分:1)

从选择器中移除<>。这创造了元素而不是选择元素。由于您希望使用href将类添加到a的li中,因此需要选择链接,然后将DOM向上移动到li。这样您就可以将类添加到正确的元素中。它应该是:

$("a[href='http://localhost/hello/5']").parent("li").addClass( "active" );