I'm trying to get a piece of text that is inside a <div class> of a especific URL and return only the content inside the <a title>. Like "<div class="test"><a title="Hello World"></a></div>" and return Hello World.
But I don't know what should do to return pieces of the text, it's returning whole html.
const fetch = require("node-fetch");
fetch('https://www.google.com/')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template)
console.log("DONE");
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
fetch('https://www.myear.sg/test.php')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(find_id_details (template))
document.getElementById("abc").innerHTML = find_id_details (template)
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
function find_id_details (input){
var part1 = input.split('<div id="abcd">')[1];
var part2 = part1.split('"></a>')[0];
var part3 = part2.split('<a title="').pop()
return part3
}
<div id="abc"> after the processing , you will get the answer </div>
You can check this answer :
your issue was : "But I don't know what should do to return pieces of the text, it's returning whole html."
lets assunme your html file is :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="abcd"> <a title="Hello World"></a></div>
<div > test 2 </div>
<div > test 3 </div>
</body>
</html>
now you will get the whole html as your response . and you want to parse the HTMl text and want to get the tag title "Hello World":
I make a custom function to parse the input HTML. now I have no idea about your HTML file.
please check the find_id_details() function .
in your code , at the place of console.log(template) , use console.log(find_id_details (template))
fetch('https://example.com/something')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(find_id_details (template))
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
function find_id_details (input){
var part1 = input.split('<div id="abcd">')[1];
var part2 = part1.split('"></a>')[0];
var part3 = part2.split('<a title="').pop()
return part3
}
This should do it:
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
Taken from node-fetch documentation https://www.npmjs.com/package/node-fetch
Or if you want to specifically get the title tag, you may use:
var titleTag = body.split('<title>')[1].split('</title>')[0];
if you want to manipulate string HTML, you have first convert it to HTML object (or parse the string). You can do it this way:
var htmlString = '<div class="test"><a title="Hello World"></a></div>';
var temp = document.createElement('div');
temp.innerHTML = htmlString;
var htmlObject = temp.firstChild;
console.log(htmlObject.getElementsByTagName("a")[0].getAttribute("title"))
//Get attribute from all elements by tag
var text = '<div class="test"><a title="Hello World"><a title="Hello Street"></a></a><a title="Hello City"></a></div>';
function getAttributeFromAllElementsByTag(htmlString, tag, attribute){
var tempArray = [];
var temp = document.createElement('div');
temp.innerHTML = htmlString;
var htmlObject = temp.firstChild;
var arrayOfElements = htmlObject.getElementsByTagName(tag);
for(var i = 0;i < arrayOfElements.length;i++){
tempArray.push(arrayOfElements[i].getAttribute(attribute))
}
return tempArray
}
console.log(getAttributeFromAllElementsByTag(text, "a", "title"))
Related
So I'm trying to build a JS script that allows me to automatically enroll in courses in uni once they're available, and what I've gotten so far is filling the boxes with course IDs and then clicking submit but then I realized using ajax to post would be a better way than simulating a click.
The problem is, the returned html after a post is just a normal html with no success msg on enrolling neither failure. Here is my code:
const courses = ['56895', '56712', '56812']
function findnewreg() {
var index = 0
courses.forEach(element => {
index++;
var ind = "crn_id" + index;
document.getElementById(ind).value = element
form = document.getElementById(ind).form
});
var regbtn = document.getElementsByName('REG_BTN')
regbtn.forEach(element =>{
if(element.value=='تنفيذ التغييرات'){
//element.click();//<form action="/PROD/xwckcoms.P_Regs" method="post" onSubmit="return checkSubmit()">
submitForm()
console.log("clicked")
document.addEventListener("DOMContentLoaded", function(event){
if (document.body.textContent.includes("لقد قمت بإجراء العديد من المحاولات لتسجيل هذا الفصل الدراسي، اتصل بمكتب التسجيل للحصول على مساعدة. ")) {
console.log('⛔️ error retrying...');
//history.back();
findnewreg()
}else{
console.log('✅ success');
}});
}
})
}
function submitForm(){
var form = form = document.getElementById("crn_id1").form
var href = '/PROD/xwckcoms.P_Regs'//form.getAttribute("action");
var formData = {};
jQuery(form)?.find("input[type=text]").each(function (index, node) {
console.log(index, node)
formData[node.name] = node.value;
});
// formData = jQuery(form).serialize() //also tried this, same result
jQuery.post(href, formData).done(function (data) {
prompt('DATA:' , data)
findnewreg();
});
}
findnewreg();
I am getting undefined when I type the author name in the text box and press the button to display the quote. It seems like my button and textbox are not linked together. How can I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Quotes</title>
</head>
<body>
<label for="getQuotes">Find Quotes (Type Author Name)</label><br>
<input type = "text" id="getQuotes" name="getQuotes" placeholder="Search" style="margin:10px" size="50"/><br />
<button id="FetchQuotes" onclick="getQuote()" style="margin:10px">Fetch Quotes</button>
<p id="quotes"></p>
<p id="author"></p>
<script>
async function getQuote() {
//const author = Boolean(false);
let url = 'https://jaw1042-motivate.azurewebsites.net/quote';
let author = document.getElementById('getQuotes').value;
if(author) {
url = 'https://jaw1042-motivate.azurewebsites.net/quote?author= ';
console.log(url + author);
} else {
console.log(url);
}
fetch(url)
.then(async (response) => {
if (response.ok) {
console.log("Response code: " + response.status);
} else if (response.status === 400) {
console.log("Unable to find any quotes by specified author: " + response.status);
} else {
console.log("No quotes have been loaded: " + response.status);
}
const val = await response.json();
console.log(val);
}).then(data => {
document.getElementById('quotes').value = data;
document.getElementById('author').value = data;
console.log(data);
alert(data);
});
}
</script>
</body>
</html>
your then functions are not correct
in the direct result of the fetchAPI you can receive data and to use it you need to run .json() or .text() on it, you can't simply use that result or return it's value ( plus when you use return statement all your next codes will be unreachable)
after that you should not assign something to your data variable because it just has new Data fetched from backend, by assigning new value to data you're about to ruin new data
here is how your js should look
function getQuote() {
fetch("https://krv1022-motivate.azurewebsites.net/quote")
.then( res => res.text() )
.then( data => {
document.querySelector(".quote").value = data;
}
);
}
I also provided a fiddle for it but it can't receive data because either your URL is not correct or there is CORS issues
==============================================
one thing that I just noticed, you are receiving Author's name from end user but you are not about to send it to backend!
so perhaps this code is more complete, I assume that you want to send data using GET method and backend wants the name of author to be named getQuotes
i am trying to convert the content of an editable div to a text file and store it in azure. It's actually a css file (format) but i guess that text will have the same output. This is what i got so far:\
var sasKey = "xxxxxxxxxxxxxxx";
var blobUri = xxxxx.blob.core.windows.net";
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sasKey);
function Save() {
var blobData = document.getElementById("CONTENT").innerText;
var myBlob = new Blob(blobData, "plain/text");
blobService.createBlockBlobFromBrowserFile('style',
"test.txt",
myBlob,
(error, result) => {
if (error) {
// Handle blob error
} else {
console.log('Upload is successful');
}
});
}
HTML:
<div id="CONTENT" contenteditable="true" spellcheck="false">so here we have text</div>
<input type="button" value="save" onclick="Save()"/>
i get the following error:
Uncaught TypeError: Failed to construct 'Blob': The provided value cannot be converted to a sequence.
The Blobobject takes a list as its first parameter.
Try this instead:
var myBlob = new Blob([blobData], { type: "plain/text" });
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
to be complete this is what i used to upload a text (txt) file
<script>azure-storage.blob.min.js</script>
JS
var sasKey = "xxxxxxxxxxxxxxx";
var blobUri = xxxxx.blob.core.windows.net";
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sasKey);
function Save() {
var blobData = document.getElementById("CONTENT").innerText;
blobService.createContainerIfNotExists('container', (error, container) => {
if (error) {
// Handle create container error
} else {
console.log(container.name);
}
});
blobService.createBlockBlobFromText('container', "test.txt", blobData,
(error, result) => {
if (error) {
// Handle blob error
} else {
console.log('Upload is successful');
}
});
}
HTML
<div id="CONTENT" contenteditable="true" spellcheck="false">so here we have text</div>
<input type="button" value="save" onclick="Save()"/>
With a QR code vcard, the user scans the code with their phone and then the dialog with the "add to contacts" pops up on their phone, such as the code below:
How can I do the same but instead of a QR code scan, I want it to do the same with a button click.
I have tried the following:
var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, loadvcard);
function loadvcard(){
url = "BEGIN%3AVCARD%0AVERSION%3A3.0%0AN%3ADoe%3BJohn%0AFN%3AJohn%20Doe%0ATITLE%3A08002221111%0AORG%3AStackflowover%0AEMAIL%3BTYPE%3DINTERNET%3Ajohndoe%40gmail.com%0AEND%3AVCARD";
window.open(url);
}
You can open your vcard in the browser as a data url if you want.
Your code would be:
var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, loadvcard);
function loadvcard(){
var data = "BEGIN%3AVCARD%0AVERSION%3A3.0%0AN%3ADoe%3BJohn%0AFN%3AJohn%20Doe%0ATITLE%3A08002221111%0AORG%3AStackflowover%0AEMAIL%3BTYPE%3DINTERNET%3Ajohndoe%40gmail.com%0AEND%3AVCARD";
window.open("data:text/x-vcard;urlencoded," + data);
}
Try to use the web share api, it works.
<html>
<title>
Web Share API
</title>
<body>
<div>
<div>
<button onclick="shareVcard" id="shareFilesButton">Share Files</button>
</div>
</div>
</body>
<script>
document.getElementById('shareFilesButton').addEventListener("click", () => shareVcard())
function shareVcard() {
fetch("sample.vcf")
.then(function(response) {
return response.text()
})
.then(function(text) {
var file = new File([text], "sample.vcf", {type: 'text/vcard'});
var filesArray = [file];
var shareData = { files: filesArray };
if (navigator.canShare && navigator.canShare(shareData)) {
// Adding title afterwards as navigator.canShare just
// takes files as input
shareData.title = "vcard";
navigator.share(shareData)
.then(() => console.log('Share was successful.'))
.catch((error) => console.log('Sharing failed', error));
} else {
console.log("Your system doesn't support sharing files.");
}
});
}
</script>
</html>
I need to retrieve text from inner element. With php it so easy to use Xpath. how about in javascript? I need to retrieve from specific element with specific id too. the request under code below. Let say it doesnt problem with CORS. i installed chrome extension to solve CORS.
<html>
<head>
</head>
<body>
<script>
fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
.then(function (response) {
return response.text();
})
.then(function (html) {
var element = document.evaluate( "//div[#id='post-body-6034358444211110141']" ,document, null, XPathResult.ANY_TYPE, null );
console.log(element);
});
</script>
</body>
</html>
Use a DOMParser to convert your string to a document.
Now you can use the document to select the element inside it with the help of getElementById.
fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
.then(function (response) {
return response.text();
})
.then(function (text) {
const parser = new DOMParser();
return parser.parseFromString(text, 'text/html');
})
.then(function (html) {
var element = html.getElementById('post-body-6034358444211110141');
console.log(element.innerHTML);
});