0

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

1
  • Can we see what you have tried ? Commented Jul 10, 2018 at 11:40

3 Answers 3

1

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>

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

Comments

1

You can try the following:

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

Comments

1

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>

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.