I’m already using $("#test").load("/content/extra.html #test");
to fetch the specific div id on another local html file and show that on the main user window, it works like a charm.
But now I need to store this specific div id text data on a variable…
Already tried
Using $.get:
$.get( "/conent/extra.html #test", function( textdata ) { alert( textdata ); });
This is showing the whole page not only the #test div
Making variables and using load:
var test = $("#test"); var textdata;
test.load("/content/extra.html #test"); textdata = test;
This is showing the whole thing again xD
Conclusion
Shall I somehow use $.get and cut the specific div id I’m looking for which I don’t know how and seems very painful to me, or there’s a better approach on this?
Advertisement
Answer
Your initial selector doesn’t have to be an existing element on the page, it can be a newly created in-memory element. For example:
let newElement = $("<div/>") newElement.load("/content/extra.html #test");
Now newElement
will itself be a <div>
element, filled with the specified content from the call to .load()
. (Note of course the async nature of the operation, so it won’t be immediately available.) You can use it like any other jQuery object, getting its .html()
or .text()
as needed, etc:
let newText = newElement.text();
If at some later point you want to append it to the DOM, you can:
$("#someOtherElement").append(newElement);