简体   繁体   中英

Using JavaScript to add a JSON property value into a HTML element's attribute value

I have some "img" properties within a JSON file, which have .jpg file paths as their values (eg "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…

  1. 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);

  2. 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.

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;

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