Reputation: 35
I have some "img" properties within a JSON file, which have .jpg file paths as their values (e.g "images/image.jpg").
Im trying to add these values into the 'src' attribute of existing HTML elements, the following is what I have tried so far…
Creating text nodes from the JSON object, then trying to add those as the 'src' attribute values using the '.setAttribute()' method, which results in an object being added instead of the url path as a string.
var img = document.createElement("img"); var imgSrc = document.createTextNode(object); img.setAttribute(src, imgSrc);
Using the 'JSON.stringify()' method to convert the JSON values into strings and adding those as the img elements 'src' attribute values. This results in the src attribute being filled with the correct paths, but they are surrounded by %22, presumably representing the quotation marks that surround strings.
var img = document.createElement("img"); var imgSrc = JSON.stringify(object); img.setAttribute(src, imgSrc);
Any ideas on how I can achieve what I'm trying to do?
Thanks in advance.
Upvotes: 0
Views: 1734
Reputation: 1074028
It sounds like you have a JSON string that has already been parsed into a JavaScript object (or perhaps you're not using JSON at all, and your starting point is the object). You haven't told us what the JSON is or what the object structure is. In a comment below, you gave part of it:
"img": "_/images/image-one.jpg"
...but that would be invalid JSON just on its own. I'm going to assume the actual JSON looks like this:
{
"img": "_/images/image-one.jpg"
}
...and that it's already been parsed, so we have an object referenced from the variable object
that has a property, img
, containing the URL for the image.
To use the img
property from that object, you just refer to it:
var img = document.createElement("img");
img.src = object.img;
Upvotes: 1