简体   繁体   中英

JS: Moving an anchor with insertAdjacentHTML only appends the href, not the element

I'm trying to move an anchor tag from one element to another. When I do this, the only thing appended is the anchors href, not the element itself. Why is this and how can I fix it?

I need a solution in Javascript only as jQuery isn't being used

Thanks for any help!

Fidde: https://jsfiddle.net/p7g7mkxs/

What I've tried:

<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]);

I've also tried using different variations of selecting my elements, like getElementsByTagName or appending it differently with innerHTML - Everything I've tried has given me the same result.

You use insertAdjacentHTML with HTML (a string), not with an actual element. If you pass it an element, the element is converted to string (like String(theElement) ). In the case of an HTMLAnchorElement , that means you just get the href . Proof:

 console.log( String(document.querySelector("a")) ); 
 <a href="http://stackoverflow.com">Hey</a> 

To append an element to the end of another element's child list, use appendChild :

var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));

(To insert it elsewhere, use insertBefore . Actually, you can use insertBefore in all cases if you like, just use null as the reference element when adding to the end.)


Also note that when you only want the first match, rather than querySelectorAll(/*...*/)[0] , use querySelector(/*...*/) , which returns the first match or null .

In addition to what @tj-crowder said, you can also use outerHTML to accomplish the task:

var hello = document.querySelectorAll('.hello');

hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0].outerHTML);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM