I want to select certain HTML elements in a DIV. Something like this:
$("#foo table,tr,td,span,p" ).addClass( Myclass );
But it adds the class also outside of DIV "#foo". I.e. only the elements in div "#foo" are the class "Myclass" to add. Thanks.
I want to select certain HTML elements in a DIV. Something like this:
$("#foo table,tr,td,span,p" ).addClass( Myclass );
But it adds the class also outside of DIV "#foo". I.e. only the elements in div "#foo" are the class "Myclass" to add. Thanks.
Share Improve this question asked Oct 21, 2014 at 21:31 user3417601user3417601 1351 silver badge8 bronze badges 2-
2
$("#foo table, #foo tr, #foo td, #foo span, #foo p").addClass("Myclass");
– entropic Commented Oct 21, 2014 at 21:33 - 1 Because your selectors after the ma are generic, you need to specify #foo before each elem – tymeJV Commented Oct 21, 2014 at 21:33
5 Answers
Reset to default 7Problem: Comma ,
separates autonomous selectors. You have to select #foo
first, then select your inner elements table, tr, td, span, p
.
You can use context attribute:
$("table, tr, td, span, p", "#foo").addClass("Myclass");
or you can chain your selectors:
$("#foo").find("table, tr, td, span, p").addClass("Myclass");
You need to do it this way, each element has to have the parent id, i.e. #foo
, before it and you need to wrap your class-name, i.e. myClass
, with ""
.
$("#foo table, #foo tr, #foo td, #foo span, #foo p").addClass("Myclass");
When you add a ma, you are separating you selectors. Try
$("#foo table, #foo tr, #foo td, #foo span, #foo p" ).addClass( Myclass );
Are you intending to select the tables, tr, td, spans, and p within div with ID foo? That selector would be more like
$("#foo table,#foo tr, #foo td, #foo span, #foo p")
Your current selector is saying "all tables inside div with ID "foo" and then also all tr, td, spans, and p on the whole document
You have two ways of doing it:
Method 1:
$("#foo").find("table, tr, td, span, p").addClass("Myclass");
Method 2:
$("#foo table , #foo tr, #foo td, #foo span, #foo p").addClass("Myclass");
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745202048a4616383.html
评论列表(0条)