jQuery html() is used to get the html contents of the first element of the matched elements; While html(‘new html content’) is used to replace or set the html contents of all the matched elements.
For example, two div elements that contains same class name “AClass”.
<div class="AClass">ABC 1</div> <div class="AClass">ABC 2</div>
1. $(‘.AClass’).html()
This will get the “ABC 1” only, the second matched element “ABC 2″ will be ignore.
2. $(‘.AClass’).html(‘This is new text‘)
This will replace the html content of all the matched elements.
<div class="AClass"><b>This is new text</b></div> <div class="AClass"><b>This is new text</b></div>
jQuery html() example
<html> <head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <style type="text/css"> .htmlClass{ padding:8px; border:1px solid blue; margin-bottom:8px; } </style> </head> <body> <h1>jQuery html() example</h1> <div class="htmlClass">I‘m going to replate by something ....</div> <div class="htmlClass">I‘m going to replate by something 2....</div> <p> <button id="getHtml">html()</button> <button id="setHtml">html(‘xxx‘)</button> <button id="reset">reset</button> </p> <script type="text/javascript"> $("#getHtml").click(function () { alert($(‘.htmlClass‘).html()); }); $("#setHtml").click(function () { $(‘.htmlClass‘).html(‘<b>This is a new text</b>‘); }); $("#reset").click(function () { location.reload(); }); </script> </body> </html>
时间: 2024-10-04 23:10:30