views:

36

answers:

2

I have a string containing HTML loaded from another page, how do I extract the background property from it's body tag using Javascript?

The body tag in the string looks like this:

<body onload='init();' background='storage/images/jsb_background.jpg' link='#000000' vlink='#000000' alink='#000000' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>

Thanks!

+1  A: 

This is my answer as I understand your problem (given the limited details and no code example)...

This is also assuming that your HTML string is valid html...

var html = yourString;
var background = "";

background = $(html).find("body").attr("background");

If you aren't actually appending your HTML string to the DOM there may not be a nice and easy jQuery way to do this. You may have to parse out the background attribute by hand.

var html       = yourString;
var charStart  = html.indexOf("<body");
var charEnd    = html.indexOf(">", charStart);
var bodyTag    = html.substring(charStart,charEnd+1);
charStart      = bodyTag.indexOf("background='")+12;
charEnd        = bodyTag.indexOf("'",charStart+13);
var background = bodyTag.substring(charStart,charEnd);
Ryan
Hi Ryan, thanks for the reply.That doesn't work I'm afraid, when I do alert(background) after that it just comes back 'undefined'I asked a similar question here - http://stackoverflow.com/questions/2883542/how-do-i-load-the-background-image-from-another-page - but was advised to reword it in a new question in the hopes of finding a different solution.
bbeckford
Hmm... it could be because you're not actually appending the html to the DOM.
Ryan
+1  A: 

I patched together a regex to do this, which will search the data string variable (containing the HTML) for the background attribute of the body tag. The regex is stolen from here and modified a bit. I'm still new to regex, so I guess it can be done more fluently, but it still gets the job done

var data = /* your html */;
var regex = /body.*background=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/;
var result = regex.exec(data);
if (result.length > 1) {
    var background = result[1];
    alert(background);
}
else {
    //no match
}
Simen Echholt
Awesome, that did it!!! Thanks a lot Simen, that's a big help!! I'll post this on my other question for others too :)
bbeckford
(the answer I posted is here - http://stackoverflow.com/questions/2883542/how-do-i-load-the-background-image-from-another-page/2895703#2895703)
bbeckford