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/
Related
A friend and I are trying to learn jQuery, and we've come across a problem we just can't figure out. We're trying to use WhateverOrigin to scrape some data from a forum (we have permission to do so from the owner, he set up a test post for us to practice scraping on). The HTML we're working on is this:
<div>
<span id="msg_68" class="subject_title">
TEST: SCRAPE THE URL
</span>
</div>
Using WhateverOrigin, we can successfully pull the complete HTML of the site using
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('[INSERT URL HERE]') + '&callback=?', function(data){
alert(data.contents);
});
However, when we tried to pull that specific element's HTML or text (to check we were pulling the correct data) we either got "undefined" with html or "" with text.
The code we were using to pull it was this:
$(document).ready(function(){
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('[INSERT URL HERE]') + '&callback=?', function(data){
alert($("#msg_68 a").text());
alert($("#msg_68 a").html());
});
});
any ideas?
Thanks
When you write $("#msg_68 a"), you are trying to access this element from the DOM in your current page and not from the loaded data.
You need to select #msg_68 a elements, within the data.contents, you can either :
Parse this data into a DOM element then fetch it to get the required element:
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('[INSERT URL HERE]') + '&callback=?', function(data){
var div = $("<div><div/>");
div.html(data.contents);
alert($("#msg_68 a", div).text());
});
Or just refer to it directly with data.contents as the content is a valid HTML:
alert($("#msg_68 a", data.contents).text());
By using $("#msg_68 a") you are selecting an element from the DOM. That element is not in the DOM yet, it is stored in a variable at that moment after you get the data from ajax. To select it like that, you'd have to first insert data from ajax to your DOM. Your alternative is the "filter" function or searching within the 'data' variable context (depending on your jquery version)
Option 1:
$(data.contents).filter('#msg_68 a');
Option 2:
$("#msg_68 a", data.contents);
This is a link for an example of Edit source Code:
http://neokoenig.github.io/jQuery-gridmanager/demo/tinymce.html
the button which value is </>.
He get the code HTML even if he changes the content of the grid.
How to get the source code HTML using JavaScript or jQuery?
Thanks.
Using JavaScript
document.documentElement.outerHTML
More info
or
document.documentElement.innerHTML
More info
you can use the html method with jquery, i.e for get the whole page html like this:
$( document ).ready(function() {
console.log($("html").html());
})
I'm not sure what you want to do exactly but if you want to get raw source code from jQuery you can use the following:
var html = $('element').html();
And with pure javascript from an id
var html = document.getElementById('id').innerHTML;
or from classname
var html = document.getElementsByClassName('class').innerHTML;
And to get the content of your example (which is an editor called tinymce) you can use the command tinymce.activeEditor.getContent(); or tinyMCE.get('myTextarea').getContent()
EDIT:
If you want to listen for changes with jQuery and display to html dynamically you'd want to do something like this:
$('yourTextArea').keyup(function() {
var html = $(this).val();
$('yourElementToDisplayTheHTML').html(html);
});
I've built a simple API, just use this:
<script src="https://cdn.jsdelivr.net/gh/Parking-Master/viewsource#latest/vs.js"></script>
In your JavaScript:
getSource('https://example.com/');
in http response header, you can find "content-type" header. that header indicates how contents of page should be rendered. so, if you want to render page as plain text("source code", as you mentioned), just change that header like this -> "content-type : text/plain; charset=UTF-8"
if you can use ajax in jquery or javascript
use like this
$("button").click(function(){
$.ajax({url: "page_you_want.html", success: function(result){
alert(result);
}});
});
`var responseText = xmlhttp.responseText;
$(reponseText).$('#products href').each(function(){
this.href = "http://www.example.com" + this.href;
})
`
reponseText contains html code.
Products is a Id of Div element.
I want to pre append all the anchor elements in this div ( products ) like http://www.example.com/ followed by current href attribute.
You need to only specify the required parts in ajax request page, otherwise xmlhttp.responseText will return all the HTML and print statements given in the request page.
for example, in the case of JSP
<html>
<%
out.print("something")
%>
</html>
ajax:
xmlhttp.responseText will return both html tag and the print text 'something'
actual result will be: "<html>something</html>"
so you need to remove unwanted html/printing statements from your request page.
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.
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");
}
});