hehexd123 hehexd123 - 1 month ago 9
HTML Question

Using Toggle() to show an HTML content using jQuery

i'm trying to learn some jQuery and i need some help on this little program, like you see i have a header which contains some text and i need to make sure that it expands to it's HTML content once been clicked using

Toggle()
.

This my HTML

<body>
<div class="tog">
<h1 id="hh">
<span> Click me to see my HTML content <span>
<!-- A comment -->
</h1>
</div>
</body>


Here is my jQuery code

<script src="jquery.js"></script>
<script>

$(function ()
{
$(".tog").click(function (){
$('#hh').slideToggle("slow");

$(this).toggleClass("active");

if ($(this).text() == "Click me to see my HTML content ")
$(this).html(h1);
else
$(this).text("Click me to see my HTML content ");
});

</script>

Answer

The line $(this).html(h1); is not valid in your case, it will look for a variable named h1 not create a <h1> tag, the html() function takes only a string as an input so change your function to

$(".tog").click(function (){
  // you don't need any of the previous lines

  console.log($('#hh').html()); //this would show the comments as well

  if ($(this).text() == "Click me to see my HTML content ")
    $(this).html("<h1 id='hh'><span> Click me to see my HTML content <span><!-- A comment --></h1>");
  else
    $(this).text("Click me to see my HTML content ");
});

Check here

Comments