Sunday, 23 May 2021

Find span tag inside div tag and set any text.

The given snippet will find the all span tag inside the div tag and set new text.
 
<div id='div1' class="c1">      <span>First Div</span>    </div>
<div id='div2' class="c2">      <span>Second Div</span>    </div>
<button id='action'>Click to Perform Action</button>

JQuery code to find all span inside the div tag and set new text will be - 

$('div').find('span').text('New text');
or     
$('div').children('span').text('New text');

If we want to change only in a specific div the mention div id or class like this

$('#div1').find('span').text('New text');// using id

$('.c1').find('span').text('New text'); // using class

Complete example -

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <h3>
  Click to change 
  </h3>
<div id='div1' class="c1">      <span>First Div span text</span>    </div>
<div id='div2' class="c2">      <span>Second Div span text</span>    </div>
<button id='action'>Click to Perform Action</button>

 <script>
  $('#action').click(function() {
         $('div').find('span').text('New text'); // change all div 
      //  $('#div1').find('span').text('New text'); //only change div1 using id
     //   $('.c2').find('span').text('New text');only change div2 using class
         // or
       // $('div').children('span').text('New text');
  });
</script> 
</body>
</html>

No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...