JavaScript <div> .class Extraction - javascript

I am writing JavaScript that retrieves a webpage from another site, and only displays 'Notices' from a site.
Fortunately, all 'Notices' are div elements of class 'event'.
I want to extract only these divs from the returned code so that I can re-format and display them. All the code I have so far is working, but I'm not sure on how to extract the 'event' divs from the source code. Any ideas?
function getNotices(){
// Get the date from the form
var str = document.getElementById('formDate').value;
var year = str.slice(1,4); // Extract Year
var month = str.slice(6,7); // Extract Month
var day = str.slice(9,10); // Extract Day
// Inject correct date into URL
var link = "Raw Link";
// Write raw link to div for debugging
document.getElementById('rawLink').innerHTML = link; (debugging)
// Bounce off anyorigin.com to get the source
// Re-inject date into new link
var anyLink = "http://anyorigin.com/get?url=http%3A//ilearn.stpauls.school.nz/calendar/view.php%3Fview%3Dday%26course%3D%26cal_d%3D" + day + "%26cal_m%3D" + month + "%26cal_y%3D" + year + "&callback=?"; // Splice the date into the school link and site to bounce it off
$.getJSON('http://anyorigin.com/get?url=http%3A//ilearn.stpauls.school.nz/calendar/view.php%3Fview%3Dday%26course%3D1%26cal_d%3D30%26cal_m%3D7%26cal_y%3D2013&callback=?', function(data){
var obj = JSON.stringify(data); // Turn object into a string
document.getElementById('hopefullyTheData').innerHTML = obj; // Print string containing SPC website onto page (debugging)
});
}
Thanks guys!

Load the contents into jQuery then select by event class:
var events = $(data.contents).find('.event');

You can append only the event nodes by searching inside data.contents:
$('.event', data.contents).appendTo('#hopefullyTheData');

use $('div.event') selector to extract all the div element having class event.

Related

Convert innerHTML into a custom json with javascript

This is an example of innerHTML i get from a text editor on a web page where user can write text and add images, videos and audios.
<p>This is a<br>test</p>
<p><iframe width="560" height="315" src="https://www.youtube.com/embed/12345" frameborder="0" allowfullscreen=""></iframe></p>
<p><audio controls><source src="https://www.test.com/123/456/example.mp3"/></audio></p>
<p>end of test</p>
I save the innerHTML so i can reload the contents written by the user inside the editor, but i also need to format those information in json structure like the following:
{
"page1": {
contents: [
{"text":"This is a test"},
{"video":"https://www.youtube.com/embed/12345"},
{"audio":"https://www.test.com/123/456/example.mp3"},
{"text":"end of test"}
]
}
}
this json should be sent to the backend and saved, so a mobile app can ask for those information and display them in a customized way. Maintaining elements' order is crucial.
So, how can i obtain the above structure from innerHTML in javascript? I'm madding out on it
Hope this might give you a basic idea:
1) You need to select different keys for start text and end text like start_text and end_text.
2) Create a virtual DOM element and store the innerHTML string you have in the innerHTML of DOM element. This will help you to access DOM methods and you can achieve what you want.
Ex:
var content = '(innerHTML content)';
var d = document.createElement("DIV");
d.innerHTML = content;
var p_tags = d.querySelectorAll("p");
3) Create your preferred object structure.
Ex:
var final_content = {};
final_content["page_1"] = {};
final_content["page_1"]["content"] = [];
final_content["page_1"]["content"].push({"start_text":""});
4) Finally, you can convert object to JSON string with JSON.stringify(final_content).
If the format never changes, you can try converting innerHTML to string, then split by . This will create an array of 4 elements. Loop through each element. For strings, stripping tags from strings can easily be done with string.replace("",""). For the more complicated iframe and audio tags, use this regex "(https.*?)". It will return the src url. Then create your objects with those values.
Here's some quick pseudo code:
var aHtml = JSON.stringify(element.innerHTML).split('</p>');
var result = [];
aHtml.forEach(function(item, idx, arr){
// run regex against it, grab matching element
var match = item.match(/"(https.*?)"/,"g");
if(match){
var url = match[1]; // the url
if(match[0].indexOf('audio')> -1){
result.push({audio: url});
}else{
result.push({video: url});
}
}else{
var str = item.replace(/(<p>|<br>)/g, " ");
result.push({text: str});
}
})
console.log(result);

Creating a link tag with parameters

Hi i have a link tag that i am creating from javascript. now i want to append a parameters to that link just like below example.so that when the user clicks that button it should go to that url along with the paramenters
var id="123456789";
var data = ' click' ;
this data tag i am appending to some other element.
now i can able to call /order/product. but when i give id also it is giving error "missing arguments"!!
can anyone please help me?
You'll have to unquote the string where the variable goes
var id = "123456789";
var data = ' click' ;
Or on really up-to-date JavaScript engines that support ES2015+ template literals:
var id = "123456789";
var data = ` click`;
But that won't work on any version of IE (does on Edge).
For easy create link you can use method link(str) of String:
var id="123456789";
var linkText = " click";
var href = "/order/product/" + id;
var data = linkText.link(href);
alert(data);
To make it easier both to write and read (and debug too), I'd recommend the following variant of how to organize the code:
var id = "1234566",
// It is more understandable now that hrefLink contains id concatenated with some other string
hrefLink = "/order/product/" + id,
link = document.createElemen('a');
link.href = hrefLink;
In this way you
See what variable means what
Control what your hrefLink consists of
Follow best practises when instead of multiple lines with var statement you explicitly "show" where the declaration section is:
var a = smth1,
b = smth2;
So just by looking at this code you easier understand that that is a code chunk of variables declaration
You just need to remove the quotes from id
just like below
var id="123456789";
var data = ' click' ;
If You have id within quotes means it will take as string not a variable name and so just remove the quotes. It will work

JavaScript - find text in URL by position

This should be pretty easy but I'm struggling.
I have a button that fires a function. I want an alert to fire as well that tells me which page the user was on.
www.whatever.com/thispage1/whatever
www.whatever.com/thispage2/whatever
www.whatever.com/thispage3/whatever
So after my button is clicked, I want an alert that reads back "thispage1" or "thispage2" etc. I do not want the entire URL fed back to me. Is there a way to find text in a url based on its position or number of characters before it starts?
Look at window.location.pathname and use str.slice to extract the bit you want, with str.indexOf to find the indices to start/end at
var top_dir = window.location.pathname.slice(
1,
window.location.pathname.indexOf('/', 1)
);
Maybe this will help you get started. Key players here are window.location.pathname and string.split()
var returnPage = function() {
var urlString = window.location.pathname;
var stringArray = urlString.split("/");
return stringArray[0]; // number == whichever piece of the array you want to get
};
function myFunction() {
alert(returnPage());
}

Getting value of field with Javascript/jQuery

This is my page:
http://bryntum.com/examples/gantt-latest/examples/basic/basic.html
I want to get current value of Start and Finish date.
( I will later implement a button, that user can press and then it will get all dates and post them somewhere). At the moment I just need somehow to get the date values.
At first the values are loaded from XML, but you can change the values manually.
I tried looking into source code, but was not able to get the field IDs etc.
So how I can access those fields with JS?
In case you're still looking for JS solution:
I couln't use Jquery, does the server support it?
By using JS, since the cells do not have an ID, you can access your fields by class name:
document.getElementsByClassName("x-grid-cell-inner ");
And than iterating trough the returned array.
Complete code:
var data = document.getElementsByClassName("x-grid-cell-inner ");
var mark = 0;
var out = "";
var patt=/\d\/\d/;
for (i in data) {
var txt = new String(data[i].innerHTML);
if (patt.test(txt)) {
if (mark == 0) {
out += "start: "+txt+" ";
mark = 1;
} else {
mark = 0;
out += "end: "+txt+" ";
}
}
}
It would be totally wrong to do this with jquery - It's an Extjs component with really good documentation.
Gnt.panel.Gantt has a getStart method:
Method to get a the current start date of the scheduler view
and a getEnd method:
Method to get a the current end date of the scheduler view
http://bryntum.com/docs/#!/api/Gnt.panel.Gantt
Edit:
Try getTaskStore, then getById on the store witch will return a Task that has a StartDate and EndDate fields.
unfortunately, there's no unique id on the divs so you can't access them. but they seem to have unique class="" values:
class="x-grid-cell x-grid-cell-startdatecolumn-1011"
class="x-grid-cell x-grid-cell-enddatecolumn-1014"
create a javascript like this
document.getElementsByClassName("x-grid-cell x-grid-cell-enddatecolumn-1014")
to access them and then you can get their start and end dates

Variable as jQuery selector focus

I'm using JavaScript to copy a specific div from a page into a new page. I need to remove the ID attributes for each table in the new page.
It seems that since I'm copying content from the first page, I can filter out the IDs from the string before it is written to the second page. Can jQuery take a variable as its 'focus'? Instead of manipulating the entire DOM, manipulate a particular string?
I have a non-working version of what I'm talking about:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
$("table", htmlToCopy).removeAttr('id');
currentContent.document.open();
currentContent.document.write(htmlToCopy);
currentContent.document.close();
You need to create a jQuery object by calling $(html), manipulate it, then get the HTML back by calling html().
For example:
var currentContent = window.open('','currentContentWindow');
var htmlToCopy = '<html><head><title></title></head><body>' + window.frames[0].document.getElementById('PageContentPane').innerHTML + '</body></html>';
var newStructure = $("<div>" + htmlToCopy + "</div>");
newStructure.find("table").removeAttr('id');
currentContent.document.open();
currentContent.document.write(newElements.html());
The <div> element allows me to get its inner HTML and get the HTML you're looking for.
Who not just remove ID= as a string and forget DOM manipulation all together?
First make the string a jQuery object, then work with it:
htmlToCopy = $(htmlToCopy).find("table").removeAttr('id').end().html();

Categories

Resources