Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract script tags from a HTML string

Or any other tags :)

for eg.

  <head>
    <title>page...</title>
    <script> var a = 'abc'; </script>
    <script src="foo.js" type="text/javascript"></script>
  </head>
  <body>
    ...
    <script src="foo2.js"></script>
  </body>

(this string is a response from a ajax call)

I want to get a array with 3 strings:

  1. <script> var a = 'abc'; </script>
  2. <script src="foo.js" type="text/javascript"></script>
  3. <script src="foo2.js"></script>

How can I do that?

like image 638
Alex Avatar asked Nov 13 '11 23:11

Alex


1 Answers

Define: outerHTML function (taken from here)

jQuery.fn.outerHTML = function(s) {
return (s) ? this.before(s).remove() : jQuery("&lt;p&gt;").append(this.eq(0).clone()).html();
}

Then assume your response is stored in data you can do:

$(data).filter("script").each( function(e) { 
    // do something with $(e).outerHTML()
} );
like image 120
Strelok Avatar answered Oct 04 '22 21:10

Strelok