-1
<div class="container">
    <span class="text1">test</span>
    <span class="text2">test</span>
</div>

I want to change "text2" to a href in a javascript inside my function like this:

var x=document.getElementsByClassName("text2");  // Find the elements
x.innerHTML="<a href='https://test.com'>test</a>";    // Change the content

so the content of "text2" changes to a hyperlink called "test" which refers to "https://test.com"

2 Answers2

1

you can do it like so:

var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href=\"https://test.com\">test</a>"; // Change the content including all HTML elements that might be in there to the value specified escaping the " character
<div class="container">
    <span class="text1">test</span>
    <span class="text2">test</span>
</div>

the problem was you didn't escaped the " character you can do it also without the escaping like that:

var element = document.querySelector(".text2"); // Find the first element with the class text2
element.innerHTML = "<a href='https://test.com'>test</a>"; // Change the content including all HTML elements that might be in there to the value specified
<div class="container">
    <span class="text1">test</span>
    <span class="text2">test</span>
</div>
Saar Davidson
  • 1,312
  • 1
  • 7
  • 16
0

Not quite sure which approach you need. So here are both:

HTML

<div class="container">
  <span class="text1">test</span>
  <span class="text2">test</span>
</div>

Approach A - Replace the inner html of the target

document.querySelector(".text2").innerHTML = "<a href='https://test.com'>test</a>";

Approach B - Replace the Span with Anchor

var target = document.querySelector(".text2");
if (target) {
  var anchor = document.createElement("a");
  anchor.setAttribute("href", "https://www.test.com");
  anchor.innerHTML = target.innerHTML;
  target.replaceWith(anchor);
}
webprojohn
  • 958
  • 7
  • 14