0

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>
4
  • "expands to it's HTML content" ?? can you explain more what you are trying to achieve, as of now if i click the header, its getting replaced by the same text. Commented Oct 25, 2016 at 15:32
  • 1
    It's not exactly clear what you want to achieve. Do you want some more content to appear beneath the heading when we click the heading text? and disappear when we click heading again? Commented Oct 25, 2016 at 15:34
  • @NikhilNanjappa An empty HTML page with only a Text, when i click that text it change to show me it's HTML content with tags etc using Toggle() event. Commented Oct 25, 2016 at 15:36
  • Instead of all that code, you can just make use of $('#hh').toggleClass("hide"); Commented Oct 25, 2016 at 15:36

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hello sir, thank you for answering Your answer is correct but this Toggle shows how the HTML design looks in the page, is there anyway if i click it shows me the tags and what is inside like the comment and the span tag etc once i click
Yes a simple $('#hh').html(); would show you all the html contents including the comments inside it as well. Updated the answer & codepen
Ohh i see, thank you so much for your help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.