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

jQuery html() Syntax

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

$(selector).html(function(index, html_value){});

jQuery html() Example

File : jquery_html.html

CopyFullscreenClose Fullscreen Run
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>jQuery html() 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"><p>This is content inside a div</p></div>
    <button id="text_btn_get">Click Here</button>
    <script> 
      $(document).ready(function(){
          $("#text_btn_get").click(function() {
            $('#target_elm_get').html(function(index, html_val){
              alert('Index : '+index+' & HTML : '+html_val);
            });
          });
      });
    </script>
  </body>
</html>
Output

This is content inside a div


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

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


jQuery html() set html value

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

File : jquery_html_set.html

CopyFullscreenClose Fullscreen Run
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>jQuery html() 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"><p>This content will be replace</p></div>
    <button id="text_btn_set">Click Here to replace</button>
    <script> 
      $(document).ready(function(){
          $("#text_btn_set").click(function() {
            $('#target_elm_set').html("<span>this is new html for selected div</span>");
          });
      });
    </script>
  </body>
</html>
Output

This content will be replace


अगर आप इस element को inspect करके देखेंगे तो पाएंगे कि <div> के अंदर <p> की जगह <span> हो गया है, क्योंकि html() में हमने new html('<span>this is new html for selected div<span>') pass किया है जो , selected element के अंदर html value से replace कर देगा।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers