Reputation: 351
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
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
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
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