Get only a paragraph from http response [duplicate] - javascript

I'm looking for a way to get a HTML element from a string that contains HTML. Is it possible to use a jQuery selector to do this?
I have a Javascript function that gets an entire page from the server, but I only need one element from that page.

Yes, you can turn the string into elements, and select elements from it. Example:
var elements = $(theHtmlString);
var found = $('.FindMe', elements);

Just wrap the html text in the $ function. Like
$("<div>I want this element</div>")

If you are loading a page dynamically from a server then you can target just one element from the loaded page using the following form with .load()
$(selectorWhereToShowNewData).load('pagePath selectorForElementFromNewData');
For example:
$('#result').load('ajax/test.html #container');
Where:
#result is where the loaded page part will be displayed on the current page
ajax/test.html is the URL to which the server request is sent
#container is the element on the response page you want to display. Only that will be loaded into the element #result. The rest of the response page will not be displayed.

Just use $.filter
var html = "<div><span class='im-here'></span></div>"
var found = $(html).filter(".im-here")

You can use $.find
$(document).ready(function() {
var htmlVal = "<div><span class='im-here'>Span Value</span></div>";
var spanElement = $(htmlVal).find("span");
var spanVal = spanElement.text();
alert(spanVal);
});

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.

Load html file - and access element ID's

I have loaded a html file and "placed" it inside a div:
document.getElementById('my_div').innerHTML='<object type="text/html" data="table.html" ></object>';
Works fine, but when I try to get an element by it's ID in the table (from table.html) I get null/undefined.
var table = document.getElementById('my_table'); /* Nope! */
I guess I am doing it at the wrong time or place somehow. Can you help me please?
Best Regards
I would do this with jQuery's built-in AJAX method, .load(). Like so:
$(document).ready(function(){
$('#my_div_id').load('/filepath/table.html');
var table = $('#my_table');
// Other code, presumably :)
});

Getting element by tag name after getting a page using jQuery $.get

I am requesting a full page using $.get in jQuery and would like to get the content of a specific element. Separately, here is how things look:
$.get( "/page.html").done(function( data ) {
// get textArea.
});
and I want to get:
document.getElementByTagName("textArea")[0].value;
but I can't do getElementByTagName on data so what is the best way to do this?
I tried using find but that did not work so I ended up using filter and that returned the value of textArea that I needed:
$.get( "/page.html").done(function( data ) {
var textArea = $(data).filter("textarea")[0].innerText;
});
It's slightly different of what you are doing but i think it can help. You can call .load instead of get and add the whole page to a div say <div id="mydiv"></div>
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()})
however if you do not want mydiv to show you can hide at the beginning once the main page gets loaded and if you also don't want this div on your page you can remove it after the above task is performed.
$(document).ready(function(){
$('#mydiv').hide();
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()});
$('#mydiv').remove();
})
//str represents page.html
var str = 'gibberish gibberish <textarea class="test">hello world</textarea>gibberish';
$.each( $.parseHTML(str), function( i, el ) {
if(el.firstChild) console.log(el.firstChild);
});
Fiddle: http://jsfiddle.net/ez666/7DKDk/
You could try jquery load() function.
It will load from remote server and insert document into selected element.
It also allow us to specify a portion of remote document to be inserted.
Assume your remote textarea's id is "remote" and you want to fetch the remote content into a textarea which id is "local"
var result="";
$("#local").load("/page.html #remote", function(response, status, xhr){
result=$(this).find("#remote").val();
});
I'm not sure if you want to get the remote textarea and insert into the element of the current document.
If you just want to get the value of the remote textarea, you could just hide the load function invoking element
Hope this is helpful for you.
Since you're using jQuery anyway… have you tried $(data).find('textarea').first().val() yet?
This is assuming that data is a fragment. If it is not you will want to wrap it in a div or something first.

How to get html inside a parent element from data_response?

I'm doing an ajax call, the data_response has a single HTML element with a lot of markup inside:
<div>**code I want to retrieve**</div>
I want to get the innerHtml without the parent element, so that I put it inside another element.
Basically:
$('selector').html(**code I want to retrieve**);
How can this be done?
If the response really just contains HTML, then you can parse it easily using JQuery:
var html = $(data_response).html();
$('selector').html(html);
Edit
It's the same principle as this:
var newElement = $("<div id='foo'>stuff</div>");
$("body").append(newElement);
var theElement = $("#foo");
console.log(theElement.html());
stuff

How to Extract HTML from Content Fetched with Ajax using jQuery

I have a page, in which there are a couple of Option elements whose Value point to external pages. My aim is to use Ajax to extract the chosen Option's Value & use that to load content from external pages. E.g. When a user chooses Volleyball, I will get the 'volleyball.html' value, use Ajax to retrieve that page and load its #catalog content into the current page. Here's my code:
$("select").change(function(){
var selectedURL=$("option:selected",this).val();
if(selectedURL!=="Select One"){
$("#center").html("<p class='processing'></p>");
$.get(selectedURL,function(data){
var extractedContent=$("#catalog",data);
console.log(extractedContent); //Firebug says extractedContent is '[]'
$("#center").html(extractedContent); //Nothing is inserted inside div#content
},"html");
}
I'm not good at jQuery, and have kind of mixed and matched code from a few posts here to derive at the above. Now I'm not sure what went wrong, but nothing is loaded - the #center div block that is supposed to hold the extracted content is empty.
Can someone please help me spot just what's wrong with my code above? Many thanks in advance.
The load() method is perfect for this:
$('select').change(function () {
var selectedURL = $('option:selected', this).val();
if (selectedURL !== 'Select One') {
$('#center').html('<p class="processing"></p>').load(selectedURL + ' #catalog');
}
});
It can take only a URL, or it can take a URL followed by a selector which will only load the contents of the matched element (#catalog) into the element it is called on (#center).
You can't use $('#catalog', data) just like that. To extract content, you can create a jQuery object, and assign the HTML returned then extract from there:
var extractedContent = $('<div />').html(data).find('#catalog').html();
console.log(extractedContent);
$("#center").html(extractedContent);
$("select").change(function(){
var selectedURL=$("option:selected",this).val();
if(selectedURL!=="Select One"){
$("#center").html("<p class='processing'></p>");
$.get(selectedURL,function(data){
$("#center").html($(data).find("#catalog"));
},"html");
}
});

Categories