Trying to convert jQuery get request into parseable object - javascript

I am trying to parse a jQuery get request into an object or some other way of getting a particular div on a page.
Here's my code:
$.get("http://en.wikipedia.org/wiki/Afghanistan", function(response) {
var elements;
elements = $.html(response);
console.log(elements);
});
The only problem is that elements is not HTML to parse. Let's say I want to get a specific div on the response variable - how would I go about doing that? This is with the intention of (eventually, after some processing) copying it to a div on my local page.
Don't worry about cross domain issues - this is for a Phonegap application

Use $.parseHTML() so you can convert that response to a set of DOM nodes and later insert that to the document.
You can do it like this:
$.get("http://en.wikipedia.org/wiki/Afghanistan", function(response) {
var elements;
elements = $.parseHTML(response);
console.log(elements);
var myDiv = $(elements).find('#idForDiv');
});

It sounds like the jQuery load function does exactly what you want. You can specify a selector after the url to load a particular part of the page:
$("#mydiv").load( "http://en.wikipedia.org/wiki/Afghanistan #divonpage");
http://jqapi.com/#p=load

If the response from the server is HTML then you can wrap it in a jQuery object and act upon it.
I would vouch for this approach:
var server_response = '<div style="background-color:yellow;"><div class="find-me">Hello</div></div>';
$('span').html($(server_response).find('.find-me'));
.find-me {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span></span>

Related

Why can't I use part of this AJAX response?

I have a jQuery ajax call:
$.ajax ({
url : 'foo/bar/',
success: function(data) {
console.log(data);
var newHeaderText = $(data).find('#header-text').text();
$("#header-text").text(newHeaderText);
var newContent = $(data).find('#content').html();
console.log(newContent);
$("#content").html(newContent);
}
});
The logged data successfully shows the complete html of the target page.
The header-text section works as expected.
The console.log(newContent), however, returns undefined. Short of posting the entire html of foo/bar/ here, suffice it to say that I am quite sure a div of id content is in data, and that it has many child elements.
Why is my attempt at grabbing the content of one page and plopping it into the content of another page not working. It is especially confusing to me as header-text seems to work just fine.
You could try $.parseHTML instead:
var newContent = $($.parseHTML(data)).find('#content');
If #content is a top-level element, then the above code might still miss it. You could then solve this by first loading the HTML in container, and then find the element in there:
var newContent = $('<div>').append($.parseHTML(data)).find('#content');

Extract div data from HTML raw DIV text via JS

I'm trying to extract data from a JS function that only renders an element's HTML - and I need the element's ID or class.
Example:
JS Element Value:
x = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
I need to do get the element's id or class (in this case the id would be myId).
Is there any way to do this? Strip the tags or extract the text via strstr?
Thank you
The easiest thing to do would be to grab the jQuery object of the string you have:
$(x);
Now you have access to all the jQuery extensions on it to allow you to get/set what you need:
$(x).attr('id'); // == 'myId'
NOTE: This is obviously based on the assumption you have jQuery to use. If you don't, then the second part of my answer is - get jQuery, it's designed to make operations like these very easy and tackle compatibility issues where it can too
You may want to take a look at this:
var div = document.createElement('div');
div.innerHTML = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
console.log(div.firstChild.className);
console.log(div.firstChild.id);

Multiple classes map with Jquery and load the content

I have a Div of Class
<div class='navigation five-icons'></div>
and i want to load a URL which returns html inside it, how can i select that div with jquery,
what i have tried is
$('.navigation .five-icons').load('URL');
$('.navigation.five-icons').load('http://www.astuffaday.com/shot/menu.php');
but no use.
I dont know about loading but you can use below code to select more than one class
$('.navigation, .five-icons')
Are you trying to get the data asynchronously?
Use $.post() or $.get()
$.post('filename.php', {'name1':'value1', 'name2':'value2'}, function(result) {
alert(result); // result has the HTML content returned by filename.php
$('#resultDiv').html(result); // resultDiv will have its contents
// Now you need to get only particular div
// You can use 'find()'
// Something like this may help [Have not been tested]
var data = $('result').find('.navigation .five-icons');
alert(data);
})
References
$.ajax()
$.post()
$.get()
$.load()
.find()

Counting classes on another page and displaying them

To save me a lot of work editing a number in when adding a document to a site I decided to use javascript to count the number of elements with a class doc .
I am two main problems:
There is trouble displaying the variable. I initially thought this was because I hadn't added function, however when I tried adding this the variable was still not displayed.
The elements with the class I want to count are on another page and I have no idea how to link to it. For this I have tried var x = $('URL: /*pageURL*/ .doc').length; which hasn't worked.
Essentially I want the total elements with said class name and this to be displayed in a span element.
Currently I have something similar to what's displayed below:
<script>
var Items = $('.doc').length;
document.getElementById("display").innerHTML=Items;
</script>
<span id="display"></span>
Found an example of something similar here where the total numbers of articles are displayed.
Edit:
#ian
This code will be added to the homepage, domain.net/home.html. I want to link to the page containing this documents, domain.net/documents.html. I've seen this done somewhere before and if I remember correctly they used url:domainname.com/count somewhere in their code. Hope this helps.
Here is a jQuery call to retrieve the url "./" (this page) and parse the resulting data for all elements with class "lsep" "$('.lsep', data)". You should get back a number greater than 5 or so if you run this from within your debug console of your browser.
$.get("./", function(data, textStatus, jqXHR)
{
console.log("Instances of class: " + $('.lsep', data).length)
});
One important thing to remember is that you will run into issues if the URL your are trying to call is not in the same origin.
Here's an updated snippet of code to do what you're describing:
$(document).ready(
function ()
{
//var url = "/document.html" //this is what you'd have for url
//var container = $("#display"); //this is what you'd have for container
//var className = '.data'; //this is what you'd have for className
var url = "./"; //the document you want to parse
var container = $("#question-header"); //the container to update
var className = '.lsep'; //the class to search for
$.get(url, function (data, textStatus, jqXHR) {
$(container).html($(className, data).length);
});
}
);
If you run the above code from your browser's debug console it will replace the question header text of "Counting classes on another page and displaying them" with the count of instances the class name ".lsep" is used.
First, you have to wait until the document is ready before manipulating DOM elements, unless your code is placed after the definition of the elements you manipulate, wich is not the case in your example. You can pass a function to the $ and it will run it only when the document is ready.
$(function () {
//html() allows to set the innerHTML property of an element
$('#display').html($('.doc').length);
});
Now, if your elements belongs to another document, that obviously won't work. However, if you have used window.open to open another window wich holds the document that contains the .doc elements, you could put the above script in that page, and rely on window.opener to reference the span in the parent's window.
$('#display', opener.document.body).html($('.doc').length);
Another alternative would be to use ajax to access the content of the other page. Here, data will contain the HTML of the your_other_page.html document, wich you can then manipulate like a DOM structure using jQuery.
$.get('your_other_page.html', function(data) {
$('#display').html($('.doc', data).length);
});

How can I replace a table with a new one using jQuery?

Whats the best way to replace a <table> with a new one using jQuery? I'm using ajax on the page to get the new data.
If you don't want to add a wrapper element, something like this should work:
$.ajax({
url: 'yoururl.php',
success: function(r) {
$('table#something').replaceWith(r);
}
});
..assuming the response you get is an table element.
Wrap it in a div, and:
$("#myDiv").load("/some/url.php"); // where url.php outputs the entire table
You can specify a portion of the remote document to insert by putting it's selector with the URL parameter as follows:
$("#myDiv").load("/some/url.php #myTable");

Categories

Resources