[英]Problem adding link in anchor inside paragraph with dom
I am trying to add an href in an anchor that is inside a paragraph.我正在尝试在段落内的锚点中添加一个 href。
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我觉得这是不可能的,但我还是尝试了
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.您尝试使用
innerHTML
处理元素的方式没有错,但是您有一个必须使用的字符串,而修改此字符串的唯一方法是使用正则表达式。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.