I'm loading my website's pages with ajax by replacing the content inside the main
tag. Problem is, using Wordpress, each page has its own body
classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.
I thought i'd run a new ajax request to get the whole html page, then check for the body
element, then use .attr("class")
to get the list of class and finally replace the old body classes by the new one...
But the classes always return undefined
instead of a list of classes.
EDIT: I tried to use .cd-main-content
instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.
How can I possibly get it to work on the body
element ? (I already tried to replace .find
by .filter
but it doesn't work either.)
HTML stucture
<body id="body" class="home page-id-number other-classes">
<main>
<div class="cd-main-content">
<!-- inside is the dynamically loaded content-->
</div>
</main>
</body>
jQuery
$.ajax({url: url,
success: function(data){
var body = $(data).find("#body");
var classes = body.attr("class");
console.log(data); //returns the html as expected
console.log("body : "+body); //returns [object Object]
console.log("classes : "+classes); //returns undefined
}
});
"body" tag filtering by jQuery when getting from string.
So $(data)[0] will back all content, without body.
Also use filter, not "find" So you can get classes like that:
$.ajax({url: url,
success: function(data){
//replace body tag
data = data.replace("<body", "<container").replace("body>", "container>");
var classes = $(data).filter("container").attr("class");
$("body").attr("class", classes);
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments