Grant Smith
Grant Smith

Reputation: 351

Insert span surround link text using javascript

I'd like to surround text section of a link with a <span> tag. So that;

<a class="button" href="#">Text</a>

becomes

<a class="button" href="#"><span>Text</span></a>

I'd like to achieve this using only JavaScript, however, I am open to suggestions.

Thanks in advance for the help

Upvotes: 0

Views: 174

Answers (3)

ClaudiusDan
ClaudiusDan

Reputation: 243

This will do exactly what you asked.

This will do the job for all your elements with class button in your document

<a class="button" href="#">Text</a>
<script>
document.getElementByClassName("button").innerHTML='<span>'+document.getElementById("link1").innerHTML+'</span>';
</script>

This will be good to use if you want to do this to a certain button.

<a id="link" class="button" href="#">Text</a>
<script>
document.getElementById("link").innerHTML='<span>'+document.getElementById("link1").innerHTML+'</span>';
</script>

Upvotes: 1

Mamun
Mamun

Reputation: 68923

You can try the following:

var el = document.querySelector('.button')
el.innerHTML = '<span>' + el.textContent + '</span>'
<a class="button" href="#">Text</a>

Upvotes: 1

Suhas
Suhas

Reputation: 580

I see there is an answer. I feel this is easier to understand:

let anchor = document.querySelector(".button");
let html = anchor.innerHTML;

anchor.innerHTML = "<span>" + html + "</span>";
<a class="button" href="#">Text</a>

Upvotes: 1

Related Questions