Home > Enterprise >  Problem adding link in anchor inside paragraph with dom
Problem adding link in anchor inside paragraph with dom

Time:07-19

I am trying to add an href in an anchor that is inside a paragraph.

var newa= document.createElement('p'); 
  newa.innerHTML = "<span>Or</span> <a>make your renewal payment</a>";

I added it this way because the client needs them to have different styles with a border in the anchor only.

I tried this:

var linkdiv = document.querySelector(".renewnow"); /*parent div*/
const getlink = linkdiv.getElementsByTagName("a");
getlink.href="/newa"

I feel it's not possible to do that, but I tried it anyway

CodePudding user response:

The way you are trying to handle the element with innerHTML is not wrong, but then you have a string that you have to work with and the only way to modify this string is using Regex. But there is an easier way if you just create all required elements.

const p = document.createElement('p');
const span = document.createElement('span');
span.innerText = 'Or ';
const a = document.createElement('a');
a.innerText = 'make your renewal payment';
a.href = 'https://example.com';

p.append(span);
p.append(a);

document.body.append(p);

  • Related