1

I have a string which I want to break after every </div> and insert into an array. Following is the string.

"<DIV title='Run of Network' id='525000000'>Run of Network</DIV>
<div title='3dServer11' id='525001499'>3dServer11</div>"

I thought of using split() function, but since this is not a comma separated string, I am not able to understand exactly how should I break the string and generate a array. In the array I want the single single div entries like:

a[0] = <DIV title='Run of Network' id='525000000'>Run of Network</DIV>
a[1] = <div title='3dServer11' id='525001499'>3dServer11</div>"

Can any one help? Thanks in advance.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
milind
  • 269
  • 5
  • 7
  • 16
  • Why not render it in a container and parse tagname? – mplungjan Apr 19 '13 at 07:23
  • [Please, dont parse HTML with regex](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Jamiec Apr 19 '13 at 07:34

3 Answers3

4

I wouldn't suggest you to split HTML strings with split method or to parse it with regular expressions. It is always better to operate elements with DOM methods:

var str = "<DIV title='Run of Network' id='525000000'>Run of Network</DIV>\
           <div title='3dServer11' id='525001499'>3dServer11</div>",
    div = document.createElement("div"),
    arr = [];

div.innerHTML = str;
arr = Array.prototype.slice.call(div.getElementsByTagName("div"));
arr = arr.map(function(e) { return e.outerHTML; });  // to create strings
                                                     // out of DOM elements
console.log(arr);
Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 1
    +1. Could add `arr.forEach(function(e,i,a) { a[i] = e.outerHTML; })`, so that `arr` stores strings and not element objects. – Rikonator Apr 19 '13 at 07:41
  • @Rikonator True, but maybe [`map`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map) is better here. Anyway the OP needs to check browser compatibility to use these methods and add [shim](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map#Compatibility) if needed. – VisioN Apr 19 '13 at 07:45
  • @ VisioN the above solution does not work with IE 8 it gives me "Array.prototype.slice.call(div.getElementsByTagName("div")) JScript object expected Error"..how can I handle this. If it is not possible with the above solution can you provide another solution – milind Apr 22 '13 at 13:28
3

try

<div id="container"></div>
<script>
$(document).ready(function () {
    var str = "<div title='Run of Network' id='525000000'>Run of Network</div><div title='3dServer11' id='525001499'>3dServer11</div>";
    $("#container").html(str);
    for (i = 0; i < $("#container").children().length; i++) {
        alert($("#container").children()[i].innerHTML);
    }
});
2

Update:

Wrote a small jQuery plugin if you had a DOM element you wanted to do the same operation to:

(function($) {
    $.fn.splitDOMStringsByTag = function( selector ) {
        var resultsArray = [];

        this.find( '> ' + selector).each(function() {
            resultsArray.push( $(this)[0].outerHTML.replace( /[\s\n\r]+/g, ' ' ) );
        });

        return resultsArray;
    };
})( jQuery );

How this works:

Suppose you had the following DOM

<ul id="abc">
    <li>One </li>
    <li>Two </li>
    <li>Three </li>
    <li>Three 
        <ul>
            <li>Three point five</li>
        </ul>
    </li>
    <li>Four </li>
</ul>

You would then do the following:

var myArray = $('#abc').splitDOMStringsByTag('li'); 

And get the following Output

myArray; // console
["<li>One </li>", "<li>Two </li>", "<li>Three </li>", "<li>Three <ul> <li>Three point five</li> </ul> </li>", "<li>Four </li>"]

myArray[3] // console
"<li>Three <ul> <li>Three point five</li> </ul> </li>"

Old Answer with plain JS

var ipt = "<DIV title='Run of Network' id='525000000'>Run of Network</DIV><div title='3dServer11' id='525001499'>3dServer11</div>",
    dummyDiv = document.createElement("div"),
    divList = [],
    a = [];

dummyDiv.innerHTML = ipt;
divList = Array.prototype.slice.call(dummyDiv.getElementsByTagName("div"));

for (var i = 0; i < divList.length; i++) {
    a.push(divList[i]);
}

This would give you your desired a with

a[0] = <DIV title='Run of Network' id='525000000'>Run of Network</DIV>
a[1] = <div title='3dServer11' id='525001499'>3dServer11</div>

To get the strings, simply use a[0].outerHTML

a[0].outerHTML;

// Console Output
"<div title="Run of Network" id="525000000">Run of Network</div>"
Om Shankar
  • 7,989
  • 4
  • 34
  • 54