Reputation: 1
I am just learning jQuery and is a bit confused about this:
Let's say I need to provide a jQuery script that will add a class name of 'ourClass' to a <div>
. I would use the following code:
$("div").addClass('ourClass');
Is the above correct? After I add a classname to this specific <div>
would there be conflicts later if I want to add another classname to another specific <div>
?
Basic question help appreciated.
Upvotes: 0
Views: 118
Reputation: 1387
The JQuery selector $("div")
will select ALL div
elements on the page. Probably not what you want.
Instead, look at the parent elements and try to figure out a selector that will target the element in question.
For example...
<header>
<div>abc</div>
<div>def</div>
<div>ghi</div>
</header>
<main>
<div>jkl</div>
<div>mno</div>
<div>pqr</div>
<ul>
<li>
<div>stu</div>
</li>
</ul>
</main>
Selectors:
The selector $("header div")
will select the first three divs. If you need to select only one of these, you can use $("header div").first()
, $("header div").last()
, or $("header div").eq(1)
. (eq()
will select by index, where the index of the first element is 0
).
$("main div")
will select the last four (any div
element that is a child of main
, including "stu"). This is also equivalent to $("main").find("div")
.
$("main > div")
will select any div
that is a direct child of main
("jkl", "mno", and "pqr", but not "stu"). This is also equivalent to $("main").children("div")
.
$("main li div")
will select "stu".
Usually it's best to simply give your elements a class name or id if you need to target them with JQuery, but it's always possible to get creative with your selectors if you don't have a choice.
Upvotes: 1
Reputation: 17374
As King King points out, the above would find every div on the page and add the class ourClass to it. The selector portion of jQuery works just like CSS, so if you had a rule in your CSS that was div {background-color: blue;], it would apply a blue background to every div on the page. By providing more specificity in your selector, you can narrow, or target, specific elements on the page.
And, just like your standard mark up can have multiple classes for a single element, you can add multiple class with jQuery.
Upvotes: 0
Reputation: 74738
use .filter()
as per your comments:
$('div').filter(function(){
return $(this).css('height') === '34px'
}).addClass('ourClass');
The above code snippet adds the ourClass
css class to a div which has the height of 34px
.
Upvotes: 0
Reputation: 343
Any elements can have any number of classes. But same id should not be there in a document.
Upvotes: 0