.prepend is not a function

前端 未结 2 982
庸人自扰
庸人自扰 2021-01-24 02:31

Please consider the following sample code:



    
        

        
相关标签:
2条回答
  • 2021-01-24 02:43

    Please, kindly do not follow the low quality articles from W3Schools. For your solution:

    • The btn is not a jQuery object. It is a JavaScript HTMLElement.
    • The .prepend() function is a jQuery function.

    Your code now should be:

    $(document).ready(function(){
      $("#btn1").click(function(){
        var btn = $(this);
        btn.prepend("<b>Prepended text</b>. ");
      });
    });
    

    Working Snippet

    $(document).ready(function(){
      $("#btn1").click(function(){
        var btn = $(this);
        btn.prepend("<b>Prepended text</b>. ");
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>This is a paragraph.</p>
    <button id="btn1">Prepend text</button>

    See the working snippet above. Click on the Run Code Snippet and click the button inside.

    0 讨论(0)
  • 2021-01-24 03:07

    The error appears because createElement() returns a DOMElement which does not have an append() method; that's only available on jQuery objects. You need to either wrap the DOMElement to a jQuery object or, better yet, create the element in jQuery:

    $("#btn1").click(function(){
         var btn = $('<button />');     
         btn.prepend("<b>Prepended text</b>. ");
         // add the btn to the DOM somewhere...
    });
    
    0 讨论(0)
提交回复
热议问题