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.
$("#foo table, #foo tr, #foo td, #foo span, #foo p").addClass("Myclass");
– entropic
Commented
Oct 21, 2014 at 21:33
Problem: 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");