1

I am trying to access json API and retrieve some data for example : title , category, and images.

The problem is I cant get the source of the images.

I have tried :

  • field_image[0].src
  • field_image[0].getAttribute('src')
  • field_image[0].attr('src')
  • etc ..

but nothing worked correctly, it gives me "function not found" or "undefined".

pls help .. and thanks..

this is example of one json object that I retrieved.

Object
    body:"this is a normal text"
    field_category:"myCat"
    field_image:Array[2]
    0:
    "<img typeof="foaf:Image" src="http://rs.ksu.edu.sa/sites/rs.ksu.edu.sa/files/styles/750x407/public/2017-01-19-photo-00000063.jpg?itok=g4DouHqQ" width="750" height="407" alt="" />"
    1:
    "<img typeof="foaf:Image" src="http://rs.ksu.edu.sa/sites/rs.ksu.edu.sa/files/styles/750x407/public/20150817-img_0604.jpg?itok=zNXuoh5t" width="750" height="407" alt="" />"

    length:2
    __proto__:
    Array[0]
    field_issue:"1260"
    field_page_number:"19"
    field_sub_title:"sub"
    field_sub_title1:
    Array[0]
    field_sub_title2:
    Array[0]
    nid:"1269"
    title:"<a href="/issue-1260/1269">this is title</a>"
    __proto__:
1
  • field_image elements seems to be raw text strings, not html elements. You can use jQuery.parseHTML() if you're using jquery. Commented Feb 8, 2017 at 17:17

2 Answers 2

3

Use JQuery:

var url = $(field_image[0]).attr('src');

This will parse the HTML string for you so you can access the attributes easily.

Sign up to request clarification or add additional context in comments.

3 Comments

or if you do want to use jquery: stackoverflow.com/questions/494143/…
@ridwaili, mark the question if this provided the solution.
It's just a information, because If another user has the same problem as you, he / she will see what worked +1
1

thanks for @Andrew Monks. He provided me this link https://stackoverflow.com/questions/494143 where I found the solutin.

and here is the final solution:

I declared an attribute:

element: HTMLImageElement;

then I create this function that take html string and return the img src:

getImgSrc(htmlString){
    var div = document.createElement('div');
    div.innerHTML = htmlString;
    this.element = <HTMLImageElement>div.firstChild;
    return this.element.src;
}

and I called it here:

{{this.getImgSrc(item.field_image[0])}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.