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).
So basically I want to put <tag>
or <div class="tag">
inside the src or href attributes of another tag.
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>
.
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).
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.