I have this code:
$(document).ready(function() {
$form.find()
});
#second {
font-size: 20px;
color: green;
background: white;
text-align: center;
}
<form>
<div class="first" style="width: 301px; margin:5px 0 0 10px;">
<div id="second" style="font-size:18px; position: absolute; top: 8px; left: 5px; width: 300px; height: 42px;">Hello</div>
</div>
</form>
I have this code:
$(document).ready(function() {
$form.find()
});
#second {
font-size: 20px;
color: green;
background: white;
text-align: center;
}
<form>
<div class="first" style="width: 301px; margin:5px 0 0 10px;">
<div id="second" style="font-size:18px; position: absolute; top: 8px; left: 5px; width: 300px; height: 42px;">Hello</div>
</div>
</form>
I want to select the div
with id="second"
, in order to change the background
to red
. Is there any solution to do that using find()
.
The most important thing for me is to select that div
using it's id
.
jsFiddle
- Don't hide your code. – Mad Physicist Commented Mar 21, 2016 at 15:38
5 Answers
Reset to default 3$(document).ready(function() {
$("form").find( "div#second" ).addClass('red');
});
CSS
.red{
background-color: red;
}
$(document).ready(function() {
$("form div").find( "div" ).css( 'background-color', 'black');
});
why not just do this?
$(document).ready(function() {
$("#second").css("background-color", "red")
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="first" style="width: 301px; margin:5px 0 0 10px;">
<div id="second" style="font-size:18px; position: absolute; top: 8px; left: 5px; width: 300px; height: 42px;">Hello</div>
</div>
</form>
You can find the element by using #second
and then change the colour using this. If you want you can bind this to a click
event, or whatever way you would like to change the background-color
.
And if you're intent on using find()
you could do this, and you want to find multiple elements, you could do this
$(document).ready(function() {
$("form").find("#second, #fourth").css( "background-color", "red" );
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="first">
<div id="second">Hello</div>
<div id="third">World</div>
<div id="fourth">World</div>
</div>
</form>
You can target as many elements as you want by separating them using a ma.
Or as descend of the form:
$(document).ready(function() {
$("form").find( "div#second" ).css( 'background-color', 'red');
});
if you are sure of the div id beforehand it would probably be a little redundant using .find() as you could simply use the jquery selector $("#second")
.
If you wanted to use .find() though you just need to specify where you want the search to begin (the form in your case) and how you want to filter the search
so would be:
$("form").find("#second")
you could then chain this to .css()
or add it to a variable or whatever :)