Reputation: 103
I am learning JQuery and I am having trouble trying to write code which outputs a comma separated list in a CSV format from HTML code. I am trying to put the the titles of the images in a comma separated list.
Here is the HTML I am using:
<html>
<head>
</head>
<body>
<img src="/images/title.jpg" title="TITLE IMAGE" />
<div id="brand-container">
<div class="xyz">
<img src="/images/brand1.jpg" title="Adidas" />
<img src="/images/brand2.jpg" title="Dr Martens" />
<img src="/images/brand3.jpg" title="Fred Perry" />
<img src="/images/brand4.jpg" title="Lacoste" />
</div>
</div>
<div class="xyz">
<img src="/images/other.jpg" title="OTHER IMAGE" />
</div>
</body>
</html>
The following JQuery code is what I have tried to use.
var title = $(':').map(function() {
return this.value;
}).get().join(',');
Upvotes: 0
Views: 341
Reputation: 174
Do you mean to output all the image titles in your page?
title
attribute in an img
object is referred by $('#???').title$('#brand-container img')
instead if you want to output titles within div brand-container
; So that's the answer:
var title = $('img').map(function() {return this.title; }).get().join(',');
return
"TITLE IMAGE,Adidas,Dr Martens,Fred Perry,Lacoste,OTHER IMAGE"
Upvotes: 0
Reputation: 950
Here's a simple snippet, that may help you. What you should do is to store all the elements in a variable, then iterate trough it storing the title string in some kind of object/array. Then simply stringify the results. I hope it will help you a little.
var images = $('.xyz > img'),
results = [],
textarea = $('#csv');
$.each(images, function() {
results.push($(this).prop('title'));
});
textarea.text(results.join());
#csv {
height: 100px;
width: 400px;
padding: 5px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/images/title.jpg" title="TITLE IMAGE" />
<div id="brand-container">
<div class="xyz">
<img src="/images/brand1.jpg" title="Adidas" />
<img src="/images/brand2.jpg" title="Dr Martens" />
<img src="/images/brand3.jpg" title="Fred Perry" />
<img src="/images/brand4.jpg" title="Lacoste" />
</div>
</div>
<div class="xyz">
<img src="/images/other.jpg" title="OTHER IMAGE" />
</div>
<textarea id="csv"></textarea>
Upvotes: 1