jQuery में text() function का use किसी भी element की text value को set / get करने के लिए use किया जाता है। यह JavaScript DOM Element Property innerText की तरह ही लगभग work करती है।

jQuery text Syntax

जब हम element की text value को get करते हैं तो , by default या एक callback function accept करता है , जो target element की index और उसकी text value return करता है।

$(selector).text(function(index, text_value){});

jQuery text Example

File : jquery_text.html

CopyFullscreenClose Fullscreen Run
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>jQuery text() Example </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head> 
  <body>
    <div id="target_elm_get">This is content inside a div</div>
    <button id="text_btn_get">Click Here</button>
    <script> 
      $(document).ready(function(){
          $("#text_btn_get").click(function() {
            $('#target_elm_get').text(function(index, text){
              alert('Index : '+index+' & Text : '+text);
            });
          });
      });
    </script>
  </body>
</html>
Output
This is content inside a div

Important
हालाँकि आप अगर कुछ भी pass नहीं करते तब यह selected element की सिर्फ text value return करता है।

$("#text_btn_get").click(function() {
alert('Text Value : '+ $('#target_elm_get').text() );
});


jQuery text set text value

किसी selected element में नई text value set करने के लिए सिर्फ text value function में pass कर दिया जाता है।

File : jquery_text_set.html

CopyFullscreenClose Fullscreen Run
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>jQuery text() Set Example </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head> 
  <body>
    <div id="target_elm_set">This content will be replace</div>
    <button id="text_btn_set">Click Here to replace</button>
    <script> 
      $(document).ready(function(){
          $("#text_btn_set").click(function() {
            $('#target_elm_set').text("this is new text for selected div");
          });
      });
    </script>
  </body>
</html>
Output
This content will be replace

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers