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>
1

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

3 Comments

Why do our answers get downvotes? The question does have the jquery tag.
@ibrahimmahrir not sure. I think I have a serial downvoter today. Got quite a few which isn't normal
Anyways upvoted for sanity. Leaving to bed now. Grrrr!
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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.