我正在尝试将锚标记从一个元素移动到另一个元素。当我这样做时,唯一附加的是锚点href,而不是元素本身。为什么这样,我该如何解决?
我在Javascript中只需要一个解决方案,因为没有使用jQuery
感谢您的帮助!
Fidde: https://jsfiddle.net/p7g7mkxs/
我尝试了什么:
<p class="hello">hello</p>
<p class="hello">hello<a href="#link">LINK</a></p>
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0]);
我也尝试过使用不同的选择我的元素的变体,比如getElementsByTagName
或者用innerHTML
添加不同的内容 - 我尝试的所有内容都给了我相同的结果。
答案 0 :(得分:3)
您将insertAdjacentHTML
与 HTML (字符串)一起使用,而不是使用实际元素。如果将元素传递给它,则元素将转换为字符串(如String(theElement)
)。对于HTMLAnchorElement
,这意味着您只需获得href
。证明:
console.log(
String(document.querySelector("a"))
);
<a href="http://stackoverflow.com">Hey</a>
要将元素附加到另一个元素的子列表的末尾,请使用appendChild
:
var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));
(要将其插入其他位置,请使用insertBefore
。实际上,如果您愿意,可以在所有情况下使用insertBefore
,只需在添加到结尾时使用null
作为参考元素。 )
另请注意,当您只想要第一场比赛而不是querySelectorAll(/*...*/)[0]
时,请使用querySelector(/*...*/)
,这会返回第一场比赛或null
。
答案 1 :(得分:1)