[英]How to put <Tag> inside src / href
What I'm trying to accomplish is using DOM cloneNode() to get an element by tag name and clone it to another tag (inside URL). 我想要完成的是使用DOM cloneNode()通过标记名称获取元素并将其克隆到另一个标记(在URL内)。
So basically I want to put <tag>
or <div class="tag">
inside the src or href attributes of another tag. 所以基本上我想把
<tag>
或<div class="tag">
放在另一个标签的src或href属性中。
for example: 例如:
<body onload="myFunction()">
<script>
function myFunction() {
var itm = document.getElementsByTagName("tag1")[0].lastChild;
var cln = itm.cloneNode(true);
document.getElementsByTagName("tag2")[0].appendChild(cln);
}
</script>
<tag1>Hello.png</tag1>
<a href='http://example.com/<tag2></tag2>'> </a>
so the result should be: 所以结果应该是:
<a href='http://example.com/Hello.png'> </a>
You could use Element.setAttribute() to update the href or src attributes, by replacing the string (ie <tag2></tag2>
) using String.replace() with the innerHTML property of <tag1>
. 您可以使用Element.setAttribute()来更新href或src属性,方法是使用String.replace()替换字符串(即
<tag2></tag2>
)和<tag1>
的innerHTML属性。
Run the snippet below and press the button labeled " Copy ". 运行下面的代码段并按下标有“ 复制 ”的按钮。 Note that encodeURI() is used because the
<tag2>
is actually encoded as far as the DOM property is concerned (ie it isn't a separate HTML tag). 请注意,使用encodeURI()是因为
<tag2>
实际上就DOM属性而言是编码的(即它不是单独的HTML标记)。
document.addEventListener('DOMContentLoaded', function(DOMLoadEvent) { document.getElementById('copy').addEventListener('click', copyTag1); }); function copyTag1() { var innerHTML = document.getElementsByTagName("tag1")[0].innerHTML; var link = document.getElementById('link'); console.log('link.href before: ',link.href, 'innerhtml: ',innerHTML); link.setAttribute('href', link.href.replace(encodeURI('<tag2></tag2>'),innerHTML)); console.log('link.href after: ',link.href); }
<button id="copy">Copy</button> <tag1>Hello.png</tag1> <a id="link" href='http://example.com/<tag2></tag2>'> Example Link</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.