user3758078
user3758078

Reputation:

Get Body Tag Style Attribute Content

I have a string of HTML code stored in a variable

var contents = "<html><body style='background-color:red; background-attachment:fixed; margin:20px; display:block; background-size:cover;'></body></html>"

How can I get the content within the style attribute, or any other attribute in the body tag?

EDIT: for the answers below the html and body tags are removed when converting string into elements. Sorry I just realized this and it would actually need to get it from the plain string.

Upvotes: 0

Views: 1131

Answers (4)

davidkonrad
davidkonrad

Reputation: 85528

I would use a DOMParser :

var parser = new DOMParser(),
    doc = parser.parseFromString(contents, "text/html"),
    style = doc.querySelector('body').getAttribute('style');

console.log(style);

demo -> http://jsfiddle.net/a2hua4ju/

jQuery strips certain tags out, and injecting the sample string (or the like, guess that is only for demonstration purposes) to the DOM is not a good idea.

Upvotes: 0

Sean Wessell
Sean Wessell

Reputation: 3510

You can use DOMParser();

var htmlString = "<html><body style='background-color:red; background-attachment:fixed; margin:20px; display:block; background-size:cover;'><p>test</p></body></html>"

var dp = new DOMParser();
var context = dp.parseFromString(htmlString, "text/html");

var $contextBody = $(context).find('body');
console.log($contextBody.attr('style'));

DOMParser is supported in modern browsers but you should check here for compatibility. http://caniuse.com/#feat=xml-serializer

Upvotes: 2

Scaramouche
Scaramouche

Reputation: 3257

You can use:
1-

var style = $('body').prop('style');

to get an object of type: CSS2Properties.

2-

var style = $('body').attr('style');

to get a string with all the contents of style attribute.

Upvotes: -1

Someone
Someone

Reputation: 3568

If you're using jQuery, you could try;

var css = $(body).prop('css');

or if you're not;

var css = document.body.getAttribute('css');

Edit

Ah, if you're looking to get it from your variable, that's slightly different. You might have some success with (untested);

var css = contentsHTML.find('body').prop('css');

Upvotes: 0

Related Questions