0

I have an array of two objects like this:

x = {
        word: "Gun",
        pic: "<img id='pic' src='images/stimuli/gun.gif'/>",
    }, {
        word: "Hammer",
        pic: "<img id='pic' src='images/stimuli/hammer.gif'/>",
    }

I have to compare the first element of this array via the src attribute to another image tag y:

<img id="pic11" height="115" width="90" src="images/stimuli/gun.gif"/>

And I tried this comparison and it gives "undefined is not a function":

x[0].pic.attr('src') == pic11.src

If I log to console like this: console.log($(x[0].pic).attr('src')) it works I get images/stimuli/gun.gif but I cannot access via the variable x in my script.

In other words, I fail to access the src attribute of the img tag of the object in my array. How do I do that?

5
  • 1
    Did you do $(x[0].pic).attr('src') in your script? Commented Jul 28, 2014 at 19:06
  • 1
    Why do you expect this to work x[0].pic.attr('src')? Your pic is a string, not a jQuery element. Check the console, there should be a nice error in there with some clue. Commented Jul 28, 2014 at 19:06
  • I believe the syntax would work if x was an array of objects x = [{}, {}];. But the value of x in the example you posted would just be the first object x = {}, {} Commented Jul 28, 2014 at 19:11
  • "If I log to console like this: console.log($(x[0].pic).attr('src')) it works" ... then use that :) Commented Jul 28, 2014 at 19:12
  • correct your code and put two [ ] around it to make it an array. Commented Jul 28, 2014 at 19:15

3 Answers 3

1

Create a jQuery object from the pic attribute and use the .attr() like you were wanting to.

var img1 = $(x[0].pic);
var src = img1.attr('src');
Sign up to request clarification or add additional context in comments.

1 Comment

The OP seems to know about this already: "If I log to console like this: console.log($(x[0].pic).attr('src')) it works"
1

Wrap the tag image tag that you need to access in a jquery wrapper and then try and get the src attribute.

var src = $(x[0].pic).attr('src');

Comments

1

x[0].pic returns a string and not HTML code. So what you need is, convert this String to HTML code and then use $(selector).attr() on it. Below is the changed code:

$($.parseHTML(x[0].pic)).attr('src') == pic11.src

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.