Reputation: 1764
Say if I have a following block of code
<div id='demo'>
<div class='ui-demo first'>
<p></p>
</div>
<div class='ui-demo second'>
<p></p>
</div>
<div>
Is following way correct to get to the 'p' tag under the div with 'ui-demo second' class?
$('#demo').find('.ui-demo second').find('p')
Or will this line also work?
$('#demo').children('.ui-demo second').find('p')
I tried to console.log both but I wasn't sure if its working or not. I want to append a list inside the p tag, but only for the p for the 2nd children, and not the first one.
Thanks
Upvotes: 1
Views: 30
Reputation: 21666
$('.ui-demo.second > p').text("some data for paragraph");
Since you want to append a list you can do it by
$('.ui-demo.second > p').append("<ul><li>1</li><li>2</li></ul>");
If you have some other elements which have same classnames as used above then please try to use your selectors more specifically as you can. See others' answers where they have started the selection from #demo
, but if you are sure there are no other classes in your HTML page with such names and then the solution I gave will suffice, less calculations.
Upvotes: 1
Reputation: 74738
There shouldn't be any space:
$('#demo .ui-demo.second').find('p')
or
$('#demo').find('.second p')
other than this you can use this too:
$('#demo .ui-demo:first').next('div').find('p')
Upvotes: 1
Reputation: 11750
If you use find('.ui-demo second')
you are trying to get a non existing element <second>
that is child of .ui-demo
element.
Instead use:
$('#demo').find('.ui-demo.second').find('p')
to select .ui-demo
element that also has class of .second
Upvotes: 1
Reputation: 40639
You should try,
$('#demo').find('.ui-demo.second').find('p');
// no space -------------^ in both the classes, as second is not ui-demo's child
or using a single find()
like,
$('#demo').find('.ui-demo.second p');
Read the hierarchy-selectors to understand, how it works.
Upvotes: 1