0

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!

bbeckford
  • 4,467
  • 6
  • 34
  • 48
  • You should post an example HTML string to make clear that it is the old HTML 4 `background` attribute itself and not its CSS counterpart. – Pekka May 21 '10 at 16:21

2 Answers2

2

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
}
Community
  • 1
  • 1
Simen Echholt
  • 11,243
  • 2
  • 34
  • 26
  • 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 May 24 '10 at 08:23
  • (the answer I posted is here - http://stackoverflow.com/questions/2883542/how-do-i-load-the-background-image-from-another-page/2895703#2895703) – bbeckford May 24 '10 at 08:31
1

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
  • 6,756
  • 13
  • 49
  • 68
  • 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 May 21 '10 at 16:31
  • Hmm... it could be because you're not actually appending the html to the DOM. – Ryan May 21 '10 at 16:39