Reputation: 11
This is an odd request. I am using jQuery get to AJAX request some full page html content. Once I have the content captured in an object var, I want to grab the body tag class of the captured content and replace the current DOM body class with it.
Since the content is in a var and not loaded in to the DOM jQuery is useless against it. The best tool I can think of is Regex.
I have looked for hours on the internet and found nothing.
Here is the best code I could come up with but it doesn't work...
var data = '<html class="please_god_no" id="shit"><body id="id_no" class="test22">test2 class="test1" "test3"<div id="bad" class="test5 test6">test4</div> </body></html>';
var arr = data.match(/<body class=("[\w\d]*")\sid=("[\w\d]*")>([\w\d]*)</body>/);
alert(arr);
I just want the class I don't need or want any other attributes. Any help on how to find the answer would be most helpful.
Upvotes: 1
Views: 709
Reputation: 39532
Huh, this was harder than I thought, turns out things get tricky when dealing with the body/html
elements. One needs to deal with a created html
element like so:
var s = '<html class="please_god_no"><body id="id_no" class="test22">test2 class="test1" "test3"<div id="bad" class="test5 test6">test4</div> </body></html>';
var htmlObject = document.createElement('html');
htmlObject.innerHTML = s;
var klass = htmlObject.querySelector("body").className;
document.querySelector('body').className = klass;
This is all very time-consuming. There's probably a better way to do this, why aren't you rendering body
with the classes you want? Failing that, why can't you only retrieve the classes you want via AJAX? Think about restructuring your app in future versions.
Upvotes: 4