How can I select a specific HTML element in a div

I want to select specific HTML elements in a DIV. Something like that:

$("#foo table,tr,td,span,p" ).addClass( Myclass );

But he adds the class also outside the "#foo" div. That is, only the elements in the div "#foo" are the class "Myclass" to add. Thank.

+4
source share
5 answers

Problem: A comma ,separates autonomous selectors. You must first select #fooand then select your internal elements table, tr, td, span, p.

You can use the context attribute:

$("table, tr, td, span, p", "#foo").addClass("Myclass");

or you can link your selectors:

$("#foo").find("table, tr, td, span, p").addClass("Myclass");
+7
source

, , .. #foo, , myClass, "".

$("#foo table, #foo tr, #foo td, #foo span, #foo p").addClass("Myclass");
+3

When you add a comma, you separate the selectors. Try

$("#foo table, #foo tr, #foo td, #foo span, #foo p" ).addClass( Myclass );
+2
source

Do you intend to select tables, tr, td, span and p in a div with id foo? This selector will look more like

$("#foo table,#foo tr, #foo td, #foo span, #foo p")

Your current selector says "all the tables inside the div with the identifier" foo "and then also all tr, td, spans and p for the whole document

+2
source

You have two ways to do this:

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");
+1
source

All Articles