Node.src = variableName/adding HTML image with innerHTML and variable issue - javascript

I'm trying to incorporate some images "dynamically" by saving them as variables in an array and then editing the innerHtml of some divs to include them, but the images aren't showing. I'm using img.src = varName; Here's a link to the code: https://repl.it/GBoa/1 (here's also a link to a website version where the images were uploaded: cardtestwdi.bitballoon.com). I would appreciate any help I could get.

If you want to set innerHTML using a string, you will have to provide the full HTML string. You can't create a string and then use properties for regular DOM nodes. For example, you could use the following:
var imgElement = "<img src='" + myArray[i] + "' alt='test' width='200px' height='275px'/>";
However instead of doing this I would recommend creating the node in JavaScript using document.createElement and append it to the DOM using document.appendChild:
var imgElement = document.createElement('img');
imgElement.width = 200;
imgElement.height = 275;
imgElement.src = myArray[i];
myCard[i].appendChild(imgElement); // Append the image node to the card node

Related

How to find image tags in a string in node js

I have a string with image tags like below
var str = '<img src="www.client.jpg><img src="www.custums.png">';
I have to find the image tags and src i.e I need to push the image tags into an array but right now I cannot use jsdom since I had a version problem right now in my server.So, can anyone please suggest me help to do this with not using jsdom.Thanks.
Just split the string and then filter to the urls like so;
var str = '<img src="www.client.jpg"><img src="www.custums.png">';
console.log(str.split("\"").filter(t => t.startsWith("www.")));
Your example was missing a ", it would make it so this doesn't parse correctly, but assuming the html is actually of that form but without errors it will give you just the urls.
you can use xpath to extract, the path would be //img#src. alternatively, you can use an xml to json parser ; sth like fast-xml-parser
Split the string into an array of image tag. Convert strings into HTML DOM objects as shown below. Then you can easily get the src of image tag.
var str = "<img src='www.client.jpg'><img src='www.custums.png'>";
var newstring = str.replace(/></gi, ">,<"); // Replace '><' with '>,<' so that you can split with ','
var imgs = newstring.split(",");
for(i=0; i<imgs.length; i++) {
// Create a temporary div, assign img string as its innerHTML, then gets its content
var d = document.createElement('div');
d.innerHTML = imgs[i];
// Reassign the imgs array with HTML DOM object instead of string
imgs[i] = d.firstChild;
console.log(imgs[i].src);
}

JavaScript inserting images using string variable as their URL

I'm using JavaScript to parse a XML file. One of the XML's attribute is an URL which links to an image. eg. http://localhost/pic.jpg
As the parsing goes on, I use an variable to hold each URL(which is a string variable) and hoping that I can show these images in a table.
The following is part of my code:
for(i = 0; i < row.length; i++)
{
// looping through the XML file
var Logo1 = row[i].getElementsByTagName("Logo")[0].childNodes[0].nodeValue;
//Logo1 is the string which is a URL
document.write("<img src= 'Logo1' width='256' height='128'>");
}
I use Chrome, but the images won't load....
enter image description here
Can someone help?
If Logo1 is a variable containing an image path (URL, as you say), you need to build the img tag in a way that includes the path:
document.write('<img src="' + Logo1 + '" width="256" height="128">');
This concatenates the Logo1 string variable into the rest of the tag.
That said, document.write is probably not going to work for you in the long run. you would instead create a new Image object and set its src property:
var testImage = new Image();
testImage.src = Logo1;
// add testImage to the DOM

Javascript setting the SRC of an Img to whatever there is

I have a pattern for the names of the images. The second part (in the script below it is "whatever") will be used as additional information. This part is A-z. How can I load images with such names?
var createdImg = document.createElement('img');
createdImg.setAttribute('src','firstPart_' + whatever + '_.jpg');
Just add the element to the DOM. If you are using jquery, you can do something like this:
var whatever = 'test';
$("body").append("<img src='"+ 'firstPart_' + whatever + '_.jpg' +"'>");
here is the bin

How to add an object to a html string?

I'm trying to load several images by a drop action and than resizing them and adding them as a thumbnail. The resize part is very important because the images can be very large and I want to make the thumbnails small of size.
Here is my code:
loadingGif(drop);
for (var i=0;i<files.length;i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = function(e) {
var src = e.target.result;
var img = document.createElement('img');
img.src = src;
var scale = 100/img.height;
img.height = 100;
img.width = scale*img.width;
output.push('<div id="imagecontainer"><div id="image">'+img+'</div><div id="delimage"><img src="img/del.jpg"" /></div></div>');
if(output.length == files.length) {
drop.removeChild(drop.lastChild);
drop.innerHTML += output.join('');
output.length = 0;
}
}
reader.readAsDataURL(file);
}
As you can probably tell I insert a loading gif image in my dropzone until all files are loaded (output.length == files.length). When a file is loaded I add html to an array which I will print if the load is complete. The problem is I can't seem to add the img object (I need this object to resize the image) to the html string, which seems obvious as the img is an object... So my question to you guys is: how do I do this? :)
Generally speaking, it's bad habit to play with DOM elements as strings. You should instead use the native javascript (or the library/framework you are using) commands to create the elements and set their attributes.
For example if you have an element with id "image-container" which contains all your images, you may write.
var container = document.getElementById( 'image-container' );
var img = document.createElement( 'img' );
container.appendChild( img );
Instead of a large HTML string containing all your output, you can then have only a reference to an element containing all the other elements, and either appending it to the body as soon as all the elements have been loaded, or keeping it hidden and showing it when the loading is complete.
if (output.length == files.length) {
drop.removeChild(drop.lastChild);
drop.appendChild( container );
output.length = 0;
}
Remember IDs have to be unique. There cannot be more than one element with the same ID in the same document.
HTML is parsed into elements when inserted onto the page, but that doesn't mean the two formats 1 to 1 translatable.
You could use outerHTML to translate the <img> element to a HTML string. But this wont be efficient. You are translating an element to a string only to be parsed as an element again. Kinda sloppy.
"<div id='image'>"+ img.outerHTML +"</div>"
You could build the <img> tag as a string.
"<div id='image'><img src='"+ src +"'></div>"
But that starts to get hairy too. So lastly you could append the image element after you create the other html.
drop.innerHTML = "<div class='image'></div>"
document.querySelectorAll('.image:last-child')[0].appendChild(img);
However, food for thought: when you start having this much HTML in your JS, you may want to rethink your approach a bit. It's a hard to maintain and very human error prone pattern.
As others have said, there are reasons why one would avoid/choose to use strings to represent DOM elements. Also, it's a bit of a wtf moment reading code that attempts to mix both methods of representing html elements. that said, you can skip creating the image as an element in and of itself, instead inserting the appropriate string into your result(stack?).
This would have the desired scaling effect:
var src = e.target.result;
var imgStr = "<img src='" + src + "' height='" + 100 + "'/>";
ouput.push('<div id="imagecontainer"><div id="image">'+imgStr+'</div><div id="delimage"><img src="img/del.jpg"" /></div></div>');
You can create an object with arbitrary properties, in order to hold both the image and your HTML string:
var result = {
html: '<div id="imagecontainer"><div id="image">'+img+'</div><div id="delimage"><img src="img/del.jpg"" /></div></div>',
imgTag: img
}
output.push(result);
And then later on when you iterate through the results array, you can access these parts as result.html or result.imgTag (changing the first part to whatever variable you've assigned the object to).
It does mean that you'd need to change your current output.join('') to a loop that actually iterates through the values of output and concatenates their html properties instead. If you really wanted to avoid this, you could stick the images in a separate output-style array. But this isn't as clean, and runs the risk of the two array contents becoming out-of-sync. I'd stick to having two separate properties of the same object, as cleaner and better.

Variable as jQuery selector focus

I'm using JavaScript to copy a specific div from a page into a new page. I need to remove the ID attributes for each table in the new page.
It seems that since I'm copying content from the first page, I can filter out the IDs from the string before it is written to the second page. Can jQuery take a variable as its 'focus'? Instead of manipulating the entire DOM, manipulate a particular string?
I have a non-working version of what I'm talking about:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
$("table", htmlToCopy).removeAttr('id');
currentContent.document.open();
currentContent.document.write(htmlToCopy);
currentContent.document.close();
You need to create a jQuery object by calling $(html), manipulate it, then get the HTML back by calling html().
For example:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
var newStructure = $("<div>" + htmlToCopy + "</div>");
newStructure.find("table").removeAttr('id');
currentContent.document.open();
currentContent.document.write(newElements.html());
The <div> element allows me to get its inner HTML and get the HTML you're looking for.
Who not just remove ID= as a string and forget DOM manipulation all together?
First make the string a jQuery object, then work with it:
htmlToCopy = $(htmlToCopy).find("table").removeAttr('id').end().html();

Categories

Resources