jquery / jquery

jQuery JavaScript Library
https://jquery.com
MIT License
58.93k stars 20.62k forks source link

The strange behavior generated by the append method #5467

Closed ajiho closed 1 month ago

ajiho commented 1 month ago

Bug Reports:

I don't know if this is a bug, but I think it doesn't quite fit human thinking,Mainly about this method, it exhibits different effects when the parameter is a function and when it is a single parameter

jQuery version

3.7.1

browsers

Google Chrome Chrome is already the latest version Version 123.0.6312.106 (official version) (64 bit)

html

<p>ppp</p>
<div class="container">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
</div>

js

//It will add for each target element
//$(".inner").append(document.getElementsByTagName('p'));

//This method will only add the most
$(".inner").append(function (index, html) {
   // return `<p>is html str</p>`
   return document.getElementsByTagName('p')
})

What do you expect to happen?

These two methods should produce the same effect

What actually happens?

When the parameter is a function and if it returns something similar to getElementsByTagName and returns an HTMLCollection, the strange behavior will occur. If it is a regular string, it is normal

demo

https://codepen.io/lujiahao/pen/yLrKvZB

timmywil commented 1 month ago

Thanks for opening an issue. However, according to the docs neither signature of .append accepts a NodeList as valid input. You can pass an HTML string, a single element or text node, a jQuery object, or a function returning one of those. Also, avoid trying to append elements that are already attached to the DOM elsewhere. It can result in unexpected behavior, since it's unclear whether it should clone the elements or move them. In this case, there can only be one paragraph element, and it's position is moved until it reaches the last inner element.