I am trying to show updated content in an alert box but the updated content is not showing. What is the reason?
let s = $('#prg1').html('Hello <i>coders</i>');
alert(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p id="prg1">first paragraph</p>
<h1 id="h11">first heading</h1>
<h1 id="h22">second heading</h1>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Check out the documentation:
.html( htmlString )
Returns: jQuery
It's returning the jQuery object itself. If you want the content of the element after updating it, just use $(selector).html()
.
Source: API.jQuery.com: .html()
let s = $('#prg1').html('Hello <i>coders</i>');
console.log($('#prg1').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p id="prg1">first paragraph</p>
<h1 id="h11">first heading</h1>
<h1 id="h22">second heading</h1>
</body>
</script>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You wrote all your script outside the body tag...
<body>
<p id="prg1">first paragraph</p>
<h1 id="h11">first heading</h1>
<h1 id="h22">second heading</h1>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
let s = $('#prg1').html('Hello <i>coders</i>');
alert(s);
</script>
</body>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The tag should always be inside the , preferably before the closing one.