简体   繁体   中英

How to properly appendChild(a) to a div

Please help me how to properly fix appendchild(a) in the example below. I want to add a href with target _blank in the front of the div.

This is my javascript:

  onSelection: function (feedback) {
    document.querySelector("#autoComplete").blur();
    const selection = feedback.selection.value.link;

    var a = document.createElement("a");
    a.setAttribute("href", selection);
    a.setAttribute('target', '_blank');
    PLEASE-HELP-ME-HOW-TO.appendChild(a);

This is the HTML:

<div data-id="2" class="autoComplete_result">google</div>

I need this in my HTML:

<a href=https://google.com" target="_blank">
 <div data-id="2" class="autoComplete_result">google</div>
</a>

Thank you!

try this

 var wrapper = document.createElement('a'); wrapper.href="https://www.google.com"; wrapper.target="_blank"; var li= document.querySelector('.autoComplete_result'); wrapper.appendChild(li.cloneNode(true)); li.parentNode.replaceChild(wrapper, li); console.log(wrapper.innerHTML)
 <div data-id="2" class="autoComplete_result">google</div>

As I said in my comment, this is invalid syntax. What you want is:

 <li data-id="2" class="autoComplete_result"><a href=https://google.com" target="_blank">google</a></li>

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