jQuery - How to get an element's class from ajax request - javascript

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);
}
});

Your jQuery code is wrong:
$.ajax({url: url,
success: function(data){
var body = $(data).find("body"); //not #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
}
});
The right selector is body not #body, which is an id selector
So, to change your body classes use this code:
$.ajax({url: url,
success: function(data){
var classes = $(data).find("body").attr("class"); //get the classes
$("body").attr("class", classes); //set the classes
}
});
jQuery Selectors

I found a solution, it's not ideal but it fixed the problem.
First, I have to assume that it is not possible to get the attributes of the body element as it appears to be filtered by jQuery. However it is possible to get the child elements.
I ended up adding the body classes to both the body and main elements (in the header.php file of wordpress).
Here's my code now :
HTML
<body id="body" class="home page-id-number other-classes">
<main class="home page-id-number other-classes">
<!-- if I had the possibility, I'd have added "data-body-class" instead of "class" -->
<div class="cd-main-content">
<!-- inside is the dynamically loaded content-->
</div>
</main>
</body>
jQuery
$.ajax({url: url,
success: function(data){
var classes = $(data).filter("main").attr("class"); //get the classes
$("body, main").attr("class", classes); //set the classes
}
});

Related

javascript - load html content from ajax call

I have HTML page that has Ajax call to load table content
<html>
....
<script sec:haspermission="VIEW_NOTE" th:inline='javascript'>
require(['app/agent/viewGlobalAgent'], function (){
var individualId= [[${model.agent.individual.id}]];
var agentId= [[${model.agent.id}]];
$.get("/notes/referenceTable.html?individualId="+individualId+"&agentId="+agentId, function(data){
console.log("theData " , data);
var noteList = $("#note-list-container2").value;
var fileList = $("#file-list-container2").value;
// document.getElementById("note-list-container").innerHTML = noteList;
// document.getElementById("note-file-form").innerHTML = fileList;
$("#note-list-container").html(noteList);
$("#note-file-form").html(fileList);
});
</script>
....
</html>
the html that Ajax call load
<div>
<div id="note-list-container2">
....
</div>
<div id="file-list-container2">
....
</div>
</div>
I need to access these two div on callback of Ajax call
$.get("/notes/referenceTable.html?individualId="+individualId+"&agentId="+agentId, function(data){
I tried to access them but its not working
$("#note-list-container2").value
is any way to access div in loaded html
Since you want content from within the new html returned as data you want to wrap that data in $() and query within that object
Then use text() or html() since value is only for form controls, not content elements
$.get(url, function(data) {
var $data = $(data);
var noteList = $data.find("#note-list-container2").text();// or html()
var fileList = $data.find("#file-list-container2").text();
$("#note-list-container").html(noteList);
$("#note-file-form").html(fileList);
});
jQuery.text(): Get the combined text contents of each element in
the set of matched elements, including their descendants, or set the
text contents of the matched elements
jQuery.val(): Get the current value of the first element in the
set of matched elements or set the value of every matched element.
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
A div element does not have a value....
An example:
console.log('text(): ' + $("#note-list-container2").text());
console.log('val(): ' + $("#note-list-container2").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="note-list-container2">
....
</div>
I’m guessing you’re using jQuery. The HTML contents can be accessed with .html() not with value. There is no value attribute on a div element. More importantly, you should attempt to get the contents of the element AFTER updating it, not before. Also, the selectors should match. From your example, it seems that you're attempting to get the contents for a #note-list-container2 but you're updating a #note-list-container element. One of those IDs is wrong, given your sample AJAX call output.

JQuery :first does not select first, but second

I have a JQuery script which sends a request using AJAX to the following url https://djjohal.video/video/671/index.html#gsc.tab=0 which contains information of a video song.
I actually want to parse and fetch all the details from the html content I received in the AJAX call.
The HTML page contains a total of 3 div's each having a class ".head", and among them the content of the first div is the title of the song that I want to fetch. So for that I tried using the :first selector of JQuery like this: $(PAGE).find("div.class:first").text(); where PAGE is the parsed HTML object.
What it does is that instead of selecting the actual first div, it selects the second div with the head class which contains useless information.
Here is my JavaScript Code
function action(){
let url = `https://djjohal.video/video/671/index.html#gsc.tab=0`;
LOG_INFO( "REQUEST SENT..." );
$.ajax({
url : url,
success : function(res){
LOG_INFO( "DATA RECEIVED..." );
let PAGE = $(res);
LOG_INFO( $(PAGE).find("div.head:first").text() );
}
});
}
function LOG_INFO( MSG ){
$("body").text( MSG );
console.log( MSG );
}
$(document).ready(function(){
action();
});
Here is the HTMLcontent that is received during the AJAX call
Cannot Paste the whole content in here
You can view the content via this link if supported.
view-source:https://djjohal.video/video/671/index.html#gsc.tab=0
here is the output of the code when executed.
REQUEST SENT...
DATA RECEIVED...
Select Format :
Where the text "Select Format :" is the content of the second div with the head class.
You can clearly see that the first div tag with the class "head" is the one containing the Title of the Song.
But why can't JQuery see this??
Why does the :first selector selects the second div.
What should I do ?? Please help!!
First you need to clean up your HTML
Why do you have a HEAD tag outside the HTML tags?
Also you shouldn't be putting body content inside the head section.
Try this:
$.ajax({
url : url,
success : function(data){
var responseHtml = $.parseHTML(data);
songTitle = $.trim(
$(responseHtml).filter('div.head:first').text());
alert(songTitle);
}
});
you have to use first()
$(PAGE).find("div.head").first().text();
for more information:https://api.jquery.com/first/

Load static HTML file and split into array by class

I have been working on this for days and I get close but not all the way. Most of the SO answers I have found, help me get the file contents loaded into a div or a variable but it doesn't let me then do querySelectorAll on it. So, what I need to do is load the file and then break it up into an array based on a class. Without further ado, the code:
content.txt:
<h3 class="chapter">Chapter 1</h3>
<p>Lorem</p>
<h3 class="chapter">Chapter 2</h3>
<p>Lorem</p>
Loading JS:
$.ajax({
url: "content/content.txt",
cache: false,
crossDomain: true,
success: function(html){
var div = document.createElement("div");
div.innerHTML = html;
var chapters = div.querySelectorAll('chapter');
alert(chapters.length);
}
});
Expected Result:
['<h3 class="chapter">Chapter 1</h3><p>Lorem</p>',
'<h3 class="chapter">Chapter 2</h3><p>Lorem</p>']
So this loads the file (confirmed) and I have the html in a variable. I try loading it into a dynamic DIV in the DOM to do a querySelectorAll but all it returns is {}. If I dump the innerHTML all of my content is there.
I know I am mixing vanilla JS with jQuery, but I am unsure of the proper jQuery way to go about this. Any thoughts?
The selector chapter will match all your <chapter> elements. There is no such element in HTML and there is no such element in your text file. That is why nothing matches.
align="chapter" is invalid HTML. chapter is not a valid value for the align attribute, which is obsolete anyway.
Start by writing sensible HTML. Use a class to distinguish between types of div elements.
<div class="chapter">
For that matter, consider using the <section> element instead.
Then use a class selector (instead of a type selector):
div.querySelectorAll('.chapter');

passing element by id works with pure javascript but fails with jQuery

i have this pretty simple piece of code where i get a certain id and what im trying to do is to change the element's css.
the code looks like this:
<script>
jQuery('.sitePick').click(function(event){
var site = (event.target.href.split("#")[1]); // get the id
console.log(site); // make sure i get the correct id
jQuery('#' + site).css("display" , "block"); //change css
});
</script>
the log prints the correct id of the element, and when i tried t use the same id like this : docuemnt.getElementById(site).style.display = "block"
it worked, but not when using jQuery.
what worries me the most its that even when i passed the id as is ( jQuery("#dummySite") to jQuery it still didn't work..any idea what i'm doing wrong? thx
UPDATE
the value of site is "site_buzzy.com".
I am loading jquery right at the beginning of the file, other jquery methods work.the script being loaded after the content.
You need to escape dot(s) in some way to use site string as jQuery selector.
var site = (event.target.href.split("#")[1]).replace(/\./g, "\\.");
Now this could be simplified to:
var site = event.target.hash.replace(/\./, "\\."); // get the id
jQuery(site).show();
jQuery('.sitePick').click(function(event) {
var site = event.target.hash.replace(/\./, "\\."); // get the id
jQuery(site).show(); //change css
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="sitePick" href="#site_buzzy.com">Site Pick</a>
<br />
<div id="site_buzzy.com" class="hidden">The DIV #site_buzzy.com</div>

Finding and Executing / Extracting embedded JavaScript from AJAX result using jQuery

I'm performing an AJAX request to get a generated html page. I want to find a specific div in the result and inject it into the page where the request came from. I also want to include embedded script or script links which may be inside this div. Here is a simple sample of the page I want to get with AJAX
<html>
<head>
<script>alert("don't want this")</script>
</head>
<body>
<div id='findMe'>
<p>Some content</p>
<script>alert("want only this")</script>
</div>
<script>alert("don't want this")</script>
</body>
</html>
So I only want to extract the div with ID findMe. Here's what I have in the page that's doing the request
<script>
$(document).ready(function(){
$.ajax({
url: "ajax.htm",
success: function(data){
$(data).filter("#findMe").appendTo("#output");
},
dataType: "html"
});
});
</script>
<div id='output'></div>
But the script tag is missing and no alert appears. It seems to get taken out of the div. If I do
console.log($(data))
I can see each of the script tags as a document fragement, but how to I know which one was in the div before it was popped out?
You can try:
$(data).find('#findMe').appendTo('#output');
OR
$('<div/>').append(data).filter("#findMe").appendTo("#output");
Append data to a demo div (not exists in DOM) and make filter over that.
I think instead of .filter(), which filters the current jQuery collection, you have to use .find():
$(data).find("#findMe").appendTo("#output");
But I am unsure whether the script tag will be executed or not..
I had to treat the result as XML. Find the element I'm looking for in the XML object using jQuery .find(), select the actual node (array pos 0), convert the contents of the node to a string, and inject into the output div. This is the only method I've found that executes scripts only contained in the target div.
$.ajax({
url: "ajax.htm",
success: function (data){
var node = $(data).find("#findMe")[0];
if(node.xml)
{
$("#output").html(node.xml)
}
else if(new XMLSerializer())
{
$("#output").html((new XMLSerializer()).serializeToString(node));
}
},
dataType: "xml"
});

Categories