Skip to content Skip to sidebar Skip to footer

Adding Div Around Link Using Jquery

I am adding a div around a link on click of a button. but when i click button multiple times, it adds multiple divs.
  • Solution 1:

    Here is a solution shown in a jsFiddle.

    The code story is

    HTML

    <button id="myButton">My Button</button
    

    JavaScript

    $(function() {
        $("#myButton").click(function() {
            if ($(this).parent().get(0).tagName !== "DIV") {
                $(this).wrap("<div class='myDiv'>");
            }
        });
    });
    

    What the code does is register a callback for a button click. When clicked, we ask for the parent of the button that was clicked and ask if the parent node has a tag name of "DIV" meaning it is a <div>. If it is not a div, then we wrap the button in a div and end. On the next call, the detection of the parent being a div will be true and no new div will be added.

    Solution 2:

    Why don't you just use for example a function that does what you want only on the first click?

    So only on the first click of that button adds the div, if you click other times the button, it wont do anything. This way you wont add multiple divs.

    To do that you could use for example jQuery:

    <scripttype="text/javascript">
    
        $("#firstclick").one("click",function() {
            alert("This will be displayed only once.");
        });
    
    </script>

    You can check even the jQuery API Documentation regarding one:

    http://api.jquery.com/one/

  • Post a Comment for "Adding Div Around Link Using Jquery"