Im trying to create an array of object from ul li tags using jQuery. Unfortunately I’m not able to do that. I’m pasting my code bellow.
var photos = [];
$( "#sliderContent li" ).each(function() {
var title = $(this).find(".title").html();
var image = $(this).find(".image".html());
var url = $(this).find(".url").html();
var firstline = $(this).find(".firstline").html();
var secondline = $(this).find(".secondline").html();
var slide = new Object();
slide.title = title;
slide.image = image;
slide.url = url;
slide.firstline = firstline;
slide.secondline = secondline;
photos.push(slide);
});
My HTML list ul li
<ul id="sliderContent" >
<li>
<div class="title">Stairs 1</div>
<div class="image">vacation.jpg 1</div>
<div class="url"># 1</div>
<div class="firstline">Amazing Apartment for Rent in JBR 1</div>
<div class="secondline">
<div class='row'>
<div class='col1'>ABD 1</div>
<div class='col2'>EFG 1</div>
</div>
<div class='row'>
<div class='col1'>ABD 1</div>
<div class='col2'>EFG 1</div>
</div><div class='row'>
<a class='view' href='#'></a>
<a class='arrange' href='#'></a>
</div>
</div>
</li>
</ul>
This is what i want to create.
var photos = [ {
"title" : "Stairs",
"image" : "vacation.jpg",
"url" : "",
"firstline" : "Amazing Apartment for Rent in JBR",
"secondline" : "lorem ipsum"
}, {
"title" : "Office Appartments",
"image" : "work.jpg",
"url" : "",
"firstline" : "Amazing Apartment for Rent in JBR",
"secondline" : "work?"
}];
Please tell me where did go wrong, and also how to view the content of the array photos to check the result.
Any help would be appreciated.
while we’re at it, in response to gurvinder372’s answer, you could also create the object like this:
instead of you original version:
EDIT:
now, that i took some more time… You could in this case use the jQuery.map function like this:
Remember to call this code only when the dom is ready (thus the list
sliderContentexists). if you dont know the jQuery.map function, check out its doc: http://api.jquery.com/map/