[英]Applying links via JavaScript
Hullo, I am wondering how I can add a new link around/to an element, using only JavaScript? Hullo,我想知道如何仅使用JavaScript在元素周围添加新链接吗? I am new to JavaScript, and I am sorry if this question seems stupid or too easy.
我是JavaScript新手,如果这个问题看起来很愚蠢或太容易了,我感到抱歉。
Current: 当前:
<div class="container">
<div class="content1"></div>
<div class="content2"></div>
</div>
Desired Code: 所需代码:
<div class="container">
<div class="content1"></div>
<a href="http://example.com">
<div class="content2"></div>
</a>
</div>
Just use normal DOM manipulation, nothing tricky required 只需使用普通的DOM操作,就无需棘手
const container = document.querySelector('.container'); const a = container.appendChild(document.createElement('a')); a.href = "http://example.com"; a.appendChild(document.querySelector('.content2')); console.log(container.innerHTML);
<div class="container"> <div class="content1"></div> <div class="content2"></div> </div>
Create a new a
element and create a child in that element with the same content in your div
and append the a
element in the parent of the old div
('.container') 创建一个新的
a
元素,并创建该元素的孩子与您相同内容div
并追加a
旧的父元素div
(“.container”)
var content2 = document.getElementsByClassName('content2')[0]; var container = content2.parentNode; var a = document.createElement('a'); a.setAttribute("href", "www.google.com"); container.replaceChild(a, content2); a.appendChild(content2);
<div class="container"> <div class="content1">Content1</div> <div class="content2">Content2</div> </div>
Using only pure Javascript, you can do something like this: 仅使用纯Javascript,您可以执行以下操作:
1. get your div by class (you can do using getElementById if you define an id for your div) 1.按类获取div(如果为div定义ID,则可以使用getElementById)
var mydiv = document.getElementsByClassName('content1');
2. create your anchor and set an href 2.创建锚点并设置href
var new_anchor = document.createElement("a"); new_anchor.href = "http://example.com";
3. Place the div content1 inside new anchor 3.将div content1放置在新锚点内
new_anchor.append(mydiv[0]);
4. Place your entire element inside the container again 4.将整个元素再次放入容器中
var mycontainer = document.getElementsByClassName('container'); mycontainer[0].insertBefore(new_anchor, mycontainer[0].childNodes[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.