0

I have some code here that loads an external page and of course replaces the body and it's contents. Which is fine except the body tag has some attributes I'd like to retrieve that are embedded in the tag not by .css. I can't change the pages because there are thousands of them. Any suggestions would be helpful.

code to load page:

$(document).ready(function() {
    $('[id=Page]').load($(JQCurrentPagelink).val(), function() {
});

sample body tag:

<body background="/Image/ReviewFade02.jpg" leftmargin="20" topmargin="20" marginwidth="20" marginheight="20">
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • sorry body attributes are here: background="/TracksImage/ReviewFade02.jpg" leftmargin="20" topmargin="20" marginwidth="20" marginheight="20" – Michael Lawson Aug 23 '12 at 21:22
  • It might be the browser, not JQuery that is doing this. See here: http://stackoverflow.com/questions/2488839/does-jquery-strip-some-html-elements-from-a-string-when-using-html – jonkroll Aug 23 '12 at 21:43
  • even if I have to make two calls one to grab the body tag attributes then set the body and then use .load to retrieve the file I'm fine with that, if there isn't a better way. Either that or I parse the content of all the .html pages and create a css page for each one. – Michael Lawson Aug 23 '12 at 21:51

1 Answers1

0

Try this:

$.ajax({
    url: 'page-to-load.html',
    success: function(data) {
        // load the content of the other page into #ajax-div
        $('#ajax-div').html(data);
        // a RegEx pattern to grab the opening body tag
        var pattern=new RegExp("<body.*>");
        // grab the opening body tag
        var bodyOpeningTag = pattern.exec(data)[0];
        // remove everything we don't need ('<body ', '>' and quotes)
        var bodyAttributesString = bodyOpeningTag.replace('<body ', '');
        bodyAttributesString = bodyAttributesString.replace('>', '');
        bodyAttributesString = bodyAttributesString.replace(/\"/g,'');
        // split the string into a one dimensional array ('background=/images/about.jpg', 'leftmargin=20' etc)
        var bodyAttributesArray = bodyAttributesString.split(' ');
        // split each attribute item into a [attributename, value] array
        var bodyAttributesArray2d = new Array();
        for (var i = 0; i < bodyAttributesArray.length; i++) {
            bodyAttributesArray2d[i] = bodyAttributesArray[i].split('=');   
        }
    }
});

Demo page here:

jQuery - ajax load another page and grab body attributes

Danny Connell
  • 782
  • 1
  • 8
  • 18