Reputation: 1778
I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
and also I have tried :
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ?
Upvotes: 0
Views: 179
Reputation: 485
$('div.sidebar :first-child').html('hiiiiii');
Refer here
No space needed between : and first
Upvotes: -1
Reputation: 5052
$('div.sidebar : first-child').html('<div>hi with just 1 i </div>');
Upvotes: 0
Reputation: 148180
You do not need parent >
child here also you must not have space between :
and first-child
$('div.sidebar :first-child').html('<div>hiiiiiiii</div>');
:first-child Selects all elements that are the first child of their parent.
If you just want first element then go for :first
:first Selects the first matched element.
$('div.sidebar :first').html('<div>hiiiiiiii</div>');
Upvotes: 4
Reputation: 38112
You don't need the space between :
and first-child
. When you're using space, the selector will try to match a descendant :
of div.sidebar
which will result in this syntax error:
Uncaught Error: Syntax error, unrecognized expression: div.sidebar > : first-child
So you need to remove the space:
$('div.sidebar > :first-child').html('<div>hiiiiiiii</div>');
Upvotes: 2
Reputation: 62498
you need to use :first
. it will select only the first child of div with class sidebar:
$("div.sidebar :first").html('<div>hiiiiiiii</div>');
Upvotes: 2
Reputation: 1190
Try this:
$('div.sidebar').first().html('<div>hiiiiiiii</div>');
OR
$('div.sidebar').eq(1).html('<div>hiiiiiiii</div>');
OR
$('div.sidebar')[0].html('<div>hiiiiiiii</div>');
Upvotes: 3