Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 496
FroZenViper Avatar asked Oct 19 '22 10:10

FroZenViper


1 Answers

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
like image 111
Lesley Avatar answered Oct 21 '22 05:10

Lesley