Simon
Simon

Reputation: 1

Create an array from HTML in a specific form with jQuery

I'm having problems with the following piece. I'm trying to create some gallery of my own, but I'm in the very early beginning of learning jQuery, and all this array stuff is pretty hard for me to understand..

In my CMS I have created a looped output in the following form for all elements:

<img class="content" src="path/to/image1.jpg" />
<p class="title">Description1</p>
<a class="link_img" href="http://www.somesite1.com" target="_blank">Link to Site1</a>

<img class="content" src="path/to/image2.jpg" />
<p class="title">Description2</p>
<a class="link_img" href="http://www.somesite2.com" target="_blank">Link to Site2</a>

But I need to bring it into this form (for my jQuery playground):

var myDemoImages = [
    { src: 'path/to/image1.jpg', title: 'Description1', subtitle: 'http://www.somesite1.com' },
    { src: 'path/to/image2.jpg', title: 'Description2', subtitle: 'http://www.somesite2.com' }
];

I tried something like the following, but it's mixing up values, doubling values.

$('img.content').each(function() {
    for (var k = 0; k < this.attributes.length; k++)
    {
        var attr = this.attributes[k];
        if (attr.name != 'class')
            myImages.push("src:'"+attr.value+"'");
    }
});

Also the "value" I need from the p tag is actually not a value, but shouldn't something like this work?

myImages.push(this.innerHTML);

Upvotes: 0

Views: 505

Answers (2)

seoul
seoul

Reputation: 864

  • To get the HTML content from the p tag, use the $("p").html() method.

  • To get inner text, use the .text() method :-)

Upvotes: 0

kapa
kapa

Reputation: 78671

I would do something like:

<div class="demoImage">
<img class="content" src="path/to/image1.jpg" /> 
<p class="title">Description1</p>
<a class="link_img" href="http://www.somesite1.com" target="_blank">Link to Site1</a>
</div>

Note that I added a div around your elements to make it easier to access them.

And the jQuery:

var fos=$('.demoImage').map(function () {
    var $this=$(this);
    return {
        src: $this.find('img.content').attr('src'),
        title: $this.find('p.title').html(),
        subtitle: $this.find('a.link_img').attr('href'),
    };
}).get();

jsFiddle Demo

The solution uses the .map() function which is a great tool to create any arrays out of your jQuery collections.

Upvotes: 2

Related Questions