-2

I have an any html code in a variable. For example:

var MyHTML = 
'<div>
<ul>
<li><img src="http://aaa.ru/image1.png" /></li>
<li><img src="http://aaa.ru/image2.png" /></li>
<li><img src="http://aaa.ru/image3.png" /></li>
</ul>
</div>';

How can i get src all of the images to array (var images = [])?

Toto
  • 89,455
  • 62
  • 89
  • 125
Vladimir
  • 229
  • 2
  • 16

4 Answers4

1
var imgarray = $('li img').map(function() { return this.src; }).get()
davidcondrey
  • 34,416
  • 17
  • 114
  • 136
  • This is jQuery so you need to [include the libraries](http://www.w3schools.com/jquery/jquery_install.asp) in your head. – Déjà vu Sep 12 '14 at 07:54
  • Question is somewhat unclear. Do you want the SRC's in an array before or after the HTML is outputted? – davidcondrey Sep 12 '14 at 08:05
0

If you want to parse the text, you can use this regex:

/src="([^"]+)"/

If you are using JavaScript you can do:

MyHTML.match(/src="([^"]+)"/g);
Adriien M
  • 1,165
  • 7
  • 6
0

You could use jQuery for this

// wrap the HTML into a jQuery object
var $myHTML = $(MyHTML);
// initiate a new empty array
var images = [];
// iterate through all img elements
$myHTML.find('li img').each(function() {
   // push to the array the src attribute
   images.push($(this).attr('src'));
});

Also be sure to load the jQuery library if you want to use this code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
Teo
  • 614
  • 1
  • 4
  • 13
0

You must use REGEX as @Adriien said, as your html are string and you want it pre loading. try this,

var MyHTML = 
'<div><ul><li><img src="http://aaa.ru/image1.png" /></li><li><img src="http://aaa.ru/image2.png" /></li><li><img src="http://aaa.ru/image3.png" /></li></ul></div>';
var srcRegex = /<img src="([^"]+)" \/>/ig;

var matches = [];
while (srcRegex.exec(MyHTML)) {
  matches.push(RegExp.$1);
}

//contains all cookie values
console.log(matches);

jsfiddle http://jsfiddle.net/cwva0b0g/

KyawLay
  • 403
  • 2
  • 10