Joker123
Joker123

Reputation: 7

jQuery How to change text on second element?

How to change h1 text on h1 element on second div (parent2) when click button with jQuery. Thanks!

<div id="parent1">
  <h1 class="child">Hello World</h1>
</div>
<div id="parent2">
  <h1 class="child">Hello World</h1>
</div>
<div id="parent3">
  <h1 class="child">Hello World</h1>
</div>

<button>Change</button>

Upvotes: 1

Views: 3139

Answers (5)

Subhash Shipu
Subhash Shipu

Reputation: 341

$('div:nth-child(2) > h1').text('your new text here');
$('div:nth-child(2)) //2 is the index no of div you can change as you required. like 1
&nbsp;

Upvotes: 0

Coldiary
Coldiary

Reputation: 258

Considering you want a solution based on the position, aka first h1 and second div, and not based on classes and IDs, then you have :

 $('div:nth-child(2) > h1').text('your text');

But this is just to show how it's done to select by position, @Kinduser's answer is preferable.

And to trigger the button click, refers to @splitwire's indication:

$('button').on('click', function() {
   $('div:nth-child(2) > h1').text('your text');
});

$('#example button').first().click(function () {
  $('#example div:nth-child(2) > h1').text('your text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example"> 
  <div>
    <h1>Hello World</h1>
  </div>
  <div>
    <h1>Hello World</h1>
  </div>
  <div>
    <h1>Hello World</h1>
  </div>
  <button>Change</button>
</div>

Upvotes: 1

Marcos Paulo
Marcos Paulo

Reputation: 120

Try to do something like that.

 $('button').on('click', function() {
        $('#parent2 .child').html('some text here'); 
 });

Upvotes: 0

Marius Todoran
Marius Todoran

Reputation: 55

You can do something like this:

<div id="parent1">
    <h1 class="child">Hello World</h1>
</div>
<div id="parent2">
    <h1 class="child">Hello World</h1>
</div>
<div id="parent3">
    <h1 class="child">Hello World</h1>
</div>

<button id="changeTextButton">Change</button>

And the JavaScript part:

$(document).ready(function () {
            $('#changeTextButton').click(function () {
                $('#parent2 .child').text('Custom text');
            });
        });

EDIT: The above answers with

 $('button').on('click', function () {

will create the same event for each button on your page.

Upvotes: 2

splitwire
splitwire

Reputation: 297

To expand upon Kind user's answer:

$('button').on('click', function() {
    //kind user's code here//
    $('#parent2 .child').text('text'); 
});

Upvotes: 2

Related Questions