0

I have this kind of code

<div class="test"><a href="../toto"><i class="test toto">toto</i></a></div>
<div class="test"><a href="../titi"><i class="test titi">titi</i></a></div>
<div class="test"><a href="../tutu"><i class="test tutu">tutu</i></a></div>

Note that the content of the classes is unknown but i want to have at the end an array which contain in this case :

["test toto", "test titi", "test tutu"]
Lolo
  • 527
  • 2
  • 8
  • 26

5 Answers5

2

A better way with PHP is to use XPath:

$dom = new DOMDocument();
@$dom->loadHTML($yourhtml);

$xpath = new DOMXPath($dom);

$textNodeList = $xpath->query('//div[@class="test"]/a/i/@class');

foreach ($textNodeList as $textNode) {
    echo "\n" . $textNode->nodeValue;
}

Note: as Niet the Dark Absol notices it, if the div tag has several classes, you can replace the equality with contains(), so:

$textNodeList = $xpath->query('//div[contains(@class,"test")]/a/i/@class');
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
2

Try

var j = $.map($("[class]"), function(val, key) {
  return $(val).find("[class]").attr("class")
});

var j = $.map($("[class]"), function(val, key) {
  return $(val).find("[class]").attr("class")
});
$("body").append(JSON.stringify(j, null, 4))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test"><a href="../toto"><i class="test toto">toto</i></a></div>
<div class="test"><a href="../titi"><i class="test titi">titi</i></a></div>
<div class="test"><a href="../tutu"><i class="test tutu">tutu</i></a></div>
guest271314
  • 1
  • 15
  • 104
  • 177
1

You could do it by map and get

var arr = $('.test > a > i').map(function(){
    return this.className;
}).get();
console.log(arr);
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

try this regex:

<i.+?class="(.+)"

javaScript Code:

var re = /<i.+?class="(.+)"/g;
var str = '<div class="test"><a href="../toto"><i class="test toto">toto</i></a></div>\n<div class="test"><a href="../titi"><i class="test titi">titi</i></a></div>\n<div class="test"><a href="../tutu"><i class="test tutu">tutu</i></a></div>';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
0

Using jQuery map()

var arr = [];
$('.test a i').map(function(){
    arr.push(this.className);
});
console.log(arr);

Using PHP regex

$pattern = '/<i class="test(.*)(">)/';
preg_match_all($pattern, $html, $m);
$arr = array_map(function($v){
    return "test " . $v;
}, $m[1]);

print '<pre>';
print_r($arr);
print '</pre>';

Regex Demo

MH2K9
  • 11,951
  • 7
  • 32
  • 49