Apparently I don't fully understand the 'this' selector, because it is not at all working as expected.
In the html/css below I have three identical div elements each containing an identical paragraph.
The first div, which I have given a class of 'x' shows how I expected div.y to appear. The second div, which I have given the class of 'y' is how I wrote the code originally. The third div is not affected by the jQuery and is just there to show how the divs are styled before the jQuery.
The issue I have is I expected that because the expression is targeting all paragraphs within a specific element the 'this' selector would select those paragraphs rather than the element targeted in the parent function.
Could someone please explain to me why the jQuery for class y works and the jQuery for class x doesn't?
EDIT: I am not asking HOW to get a specific result. I am asking WHY I am getting the result that I am. I want to understand better how 'this' works.
html:
<div class='x'><p>Lorem</p></div>
<div class='y'><p>Lorem</p></div>
<div><p>Lorem</p></div>
css:
div {
background-color:#658923;
height:75px;
width:75px;
margin:10px;
overflow:hidden;
}
p {
width:50px;
}
.a {
background-color:#ff5555;
}
jQuery:
$(document).ready(function() {
$('div.x').each(function() {
$('p',this).each(function(){
$(this).addClass('a').css({
'height':$(this).outerWidth()
});
});
});
$('div.y').each(function() {
$('p',this).addClass('a').css({
'height':$(this).outerWidth()
});
});
});