1

Hullo, I am wondering how I can add a new link around/to an element, using only JavaScript? I am new to JavaScript, and I am sorry if this question seems stupid or too easy.

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>
ban_javascript
  • 339
  • 1
  • 4
  • 16
  • This may help https://stackoverflow.com/questions/6938248/insert-a-div-element-as-parent. Instead of inserting a div element as in the post, you could replace it with an anchor element. Following this post, you could add the link to the anchor element https://stackoverflow.com/questions/710275/how-to-add-update-an-attribute-to-an-html-element-using-javascript. – Anh Pham May 29 '18 at 01:20

4 Answers4

3

Just use normal DOM manipulation, nothing tricky required

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

Can use jQuery wrap()

$('.content2').wrap('<a href="http://example.com">')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="content1">content 1</div>
    <div class="content2">content 2</div>
</div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

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')

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>
Kavindra
  • 1,697
  • 2
  • 14
  • 19
1

Using only pure Javascript, you can do something like this:

1. get your div by class (you can do using getElementById if you define an id for your div)

var mydiv = document.getElementsByClassName('content1');

2. create your anchor and set an href

var new_anchor = document.createElement("a"); new_anchor.href = "http://example.com";

3. Place the div content1 inside new anchor

new_anchor.append(mydiv[0]);

4. Place your entire element inside the container again

var mycontainer = document.getElementsByClassName('container'); mycontainer[0].insertBefore(new_anchor, mycontainer[0].childNodes[0])

echojn
  • 111
  • 6