简体   繁体   中英

How to add a href into a div with Javascript

I would like to add <a href='https://google.com'> after a <div> .

Here is what I've been trying:

http://jsfiddle.net/L29e4ftj/

Is there someone who could help me out please?

Thank you!

Is that how do you want this?

 <div id="autoComplete_list"> <div data-id="2" class="autoComplete_result"> <span class="autoComplete_highlighted">google</span> </div> </div> <script> var aUrl = document.createElement("a"); aUrl.setAttribute("href", "https://google.com"); aUrl.innerHTML = "<span class='autoComplete_highlighted'>Google</span>" document.querySelector("#autoComplete_list").appendChild(aUrl); </script>

Problem

The way you are selecting the div is slightly wrong.

You use getElementsByClassName() which returns a list of elements, not a single element, so you will get [div] instead of div .

Solution

You can either get the first element of that list:

document.getElementsByClassName("autoComplete_result")[0]

or use the simpler Document.querySelector :

document.querySelector(".autoComplete_result") (which returns only one element, not an array).

window.onload=function() {

    // Notice the [0] which selects ONLY the first matched element
    var mydiv = document.getElementsByClassName("autoComplete_result")[0]; 
    var a = document.createElement('a');
    a.setAttribute('href',"https://www.google.com");
    a.innerText = "google link";
    mydiv.appendChild(a);
}

Seems that the getElementsByClassName is not returning as expected, so the appendChild is not working. I tried using querySelector and is working fine. Take a look at the code snippet below:

 var mydiv = document.querySelector('.autoComplete_result'); var a = document.createElement('a'); a.setAttribute('href',"https://www.google.com"); a.innerText = "google link"; mydiv.appendChild(a);
 <body> <div id="autoComplete_list"> <div data-id="2" class="autoComplete_result"> <span class="autoComplete_highlighted">goog</span>le </div> </div> </body>

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