简体   繁体   中英

body tag class ReGex

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.

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;

JSFiddle example here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM