简体   繁体   中英

Dynamically adding anchor to paragraph element is not working

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>
<body>
<div>
    <p id="test"></p>
</div>
<script>
    var newLink = document.createElement('a'); // #1
    newLink.href = 'http://google.fr'; // #2
    document.getElementById('test').appendChild(newLink); // #3
</script>

</body>
</html>

This is not working, and I can't understand why.

  1. I create a new element <a>
  2. I add the href to this element ( <a href="http://google.fr"> )
  3. I tell JS to go and find test and add this element to the <p> tag which has test as an ID.

Why it is not working?

Try adding some content to the element as well by setting the .innerHTML property. As it is now you are just adding an empty anchor. Try something like this:

var newLink = document.createElement('a');
newLink.href = 'http://google.fr';
newLink.innerHTML = 'My anchor';
document.getElementById('test').appendChild(newLink);

使用innerHTML属性将您创建的标签附加到段落标签中。

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