简体   繁体   中英

Why does assigning a variable to itself in a Dom Object make a difference

I have a HTML String, called tinymceToHTML in my example and I had the problem that when I download this html String the images sources or hrefs were set wrongly.

My image sources looked like "/file/:id" in the original String, if I convert it into a DOM object and output the source it looks like " http://localhost:3000/file:id " which is the desired output, because then the external document can load this file. So I came up with this solution.

  var div = document.createElement('div'); div.innerHTML = tinymceToHTML; var images = div.getElementsByTagName('img'); for(var i = 0; i < images.length; i++) { images[i].src = images[i].src; } var a = div.getElementsByTagName('a'); for(var i = 0; i < a.length; i++) { a[i].href = a[i].href; } tinymceToHTML = "<html><head></head><body>" + div.innerHTML + "</body></html>"; 

My problem is that I don't know why assigning the variable to itself makes a difference in that scenario: images[i].src = images[i].src or a[i].href = a[i].href.

If I let the program show me the output with an alarm Box it tells me the URL I want, but without that assignment the program doesn't do what it should.

I hope that anybody can explain me that effect, in order to change maybe the code to make it more clear that this line is required.

I also created a fiddle example that makes it easier to show what I mean, comment out the line with the assignment, to see the other result

https://jsfiddle.net/1vabgubh/5/

The full URL of an image is just what imageElement.src returns, by definition. From MDN :

HTMLImageElement.src Is a DOMString that reflects the src HTML attribute, containing the full URL of the image including base URI.

If that's how you need them to come out in your final string, then images[i].src = images[i].src seems a reasonable and succinct way of doing it. I would just add a comment to aid understanding, something like

images[i].src = images[i].src; // force the src to be the full URI

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM