I’m looking to add ‘Hello World’ to .foo, but only if the container (product) also contains .foo2. I’ve got half way with the following code, however it adds the appended text to all instances of .foo, not just the specify product containers that also have .foo2.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add text to foo if product contains foo2</title>
<style>
.product {
width: 300px;
border: 1px #333 solid;
margin-bottom: 2%;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(function() {
if($('.product > .foo2').length > 0){
$(".foo").append("Hello World");
}
});
</script>
</head>
<body>
<!-- Div 1 -->
<div class="product">
1
<div class="foo"></div>
</div>
<!-- Div 2 -->
<div class="product">
2
<div class="foo"></div>
<div class="foo2"></div>
</div>
<!-- Div 3 -->
<div class="product">
3
<div class="foo"></div>
</div>
</body>
</html>
Thanks for any help.
You need to operate on each
.productindividually with.each():