Why assigning a variable to itself in a Dom object makes a difference

I have an HTML string called tinymceToHTML in my example, and I had a problem: when I load this html string, the image sources or hrefs were set incorrectly.

My image sources looked like "/ file /: id" in the original String, if I converted it to a DOM object and output the source code, it looks like " http: // localhost: 3000 / file: id ", which is the desired result, because then an 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 the purpose of this variable in itself matters in this scenario: images [i] .src = images [i] .src or [i] .href = a [i] .href.

If I let the program show me the output with an alarm, it tells me the URL that I want, but without this destination, the program does not do what it should.

I hope someone can explain this effect to me in order to possibly modify the code to make it more clear that this line is required.

I also created an example script that makes it easier to display what I mean by commenting out the line with the purpose to see a different result

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

+5
source share
1 answer

The full image URL is what imageElement.src returns by definition. From MDN :

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

If you need them to appear on your last line, then images[i].src = images[i].src seems like a reasonable and concise way to do this. I would just add a comment to help understand something like

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

All Articles