this is the piece of code that I am using in a loop to append an HTML element to a Google Chrome Extension's popup(.html):
'wordlist' is an array of words.
'rand' is the Random number generating function.
Code:
for (l=1; l<11; l++) {
var i = rand(wordlist.length;
var h1 = document.createElement("h1");
h1.innerHTML = wordlist[i];
document.body.appendChild(h1);
}
There are no pre-existing HTML elements. So, this code is appending 10 random words to a blank page.
Now, instead of the words being appended to the page, I want to append links to the page (eg: http://dictionary.reference.com/browse/**wordlist[i]**, which is basically a dictionary.com query for that particular word). Also, I want this link to be opened in a new Chrome tab when clicked. How do I do this?
P.S: I started learning HTML and JS a day before, and I was too excited to start writing some code. I apologize if I have overlooked a simple Google solution to my problem. Thank you for your time.
for (l=1; l<11; l++) {
var i = rand(wordlist.length);
var a = document.createElement("a");
a.setAttribute('href', 'http://dictionary.reference.com/browse/'.wordlist[i]);
a.setAttribute('target', '_blank');
h1.innerHTML = wordlist[i];
document.body.appendChild(a);
}
Basicly just change h1 to a.
Also set the attribute href (the link) and target (where it should be openend).
If you want to work with the DOM,
for (l=1; l<11; l++) {
var i = rand(wordlist.length;
var a = document.createElement("a");
a.href = "http://dictionary.reference.com/browse/" + wordlist[i];
a.appendChild(document.createTextElement(wordlist[i]));
document.body.appendChild(h1);
}
The following will be faster, since you'll append the HTML only once (and DOM operations are costly):
var html = "";
for (l=1; l<11; l++) {
var i = rand(wordlist.length);
html += "<a href='http://dictionary.reference.com/browse/" + wordlist[i] + "'>"
+ wordlist[i]
+ "</a>";
}
document.body.innerHTML += html;
Try changing your code to the following:
for (l=1; l<11; l++) {
var i = rand(wordlist.length);
var a = document.createElement("a");
a.innerHTML = wordlist[i];
a.href = "http://dictionary.reference.com/browse/" + wordlist[i];
document.body.appendChild(a);
}
I fixed a problem in line 2, you'd omitted a closing parenthesis.
I also more obviously changed your h1 to an a, and added a line that sets its href.
Well its as easy as changing
h1.innerHTML = wordlist[i];
to exatly what you are after, namely:
h1.innerHTML = "<a href='http://dictionary.reference.com/browse/"+wordlist[i]+"' target='_blank'>"+wordlist[i]+"</a>";
To make it open in a new tab you have to add the attribute "target" and give it a value of blank. I think its deprecated in HTML 5 though...
Related
user = "1401";
document.write("User|"+CallSINIMethod("GetValue", ["UserField", "UserProfileFirstName", user])+"|<br><br>");
docs = CallSINIMethod("GetListValue", ["UserListProperty", "OrderedDocuments", user]);
i = 0;
while (i < docs.length) {
document.write(CallSINIMethod("GetValue", ["DocumentProperty", "ProductName", docs[i]])+"|"+docs[i]+"|<br>");
document.write("http://goodsamstorefront.com/goodsamstorefront/GetProof.aspx?id="+docs[i]+"<br>");
document.write(CallSINIMethod("GetValue", ["VariableValue", "__DateUpdatedInCart", docs[i]])+"<br>");
document.write(CallSINIMethod("GetValue", ["VariableValue", "__DocumentStatus", docs[i]])+"<br>");
document.write(CallSINIMethod("GetValue", ["DocumentProperty", "EditingStatus", docs[i]])+"<br><br/>");
i++;
}
To make the link clickable you should use the <a> tag. For example:
https://google.com
Is a link that both goes to Google and says "https://google.com"
You need to create an <a></a> tag like below:
document.write("http://goodsamstorefront.com/goodsamstorefront/GetProof.aspx?id=1<br>");
document.write("<a href='http://goodsamstorefront.com/goodsamstorefront/GetProof.aspx?id=1'>I am a Link</a><br>");
document.write as below should work
document.write("");
or you can create a elements
var a = document.createElement('a');
a.setAttribute('href',link);
a.innerHTML = text;
and append but its a lengthy way way
Basically I am trying to find the most efficient way to simply add an image to each question. The text works fine if I just use that. But the images don't display and I am new to Javascript. Any help would be appreciated.
I have declared an array as follows: it should have an image for the question, an array of answers for the choices, and an answer.
var questions=[
new Question("http://path/hombre.jpg",["man","day","weather","time"],"man"),
new Question("http://path/day.jpg", ["year","thing","part/portion","day"],"year"),];
Here is the function that populates the questions in the app. There is more code in js and html of course however I would like to know if there is a command or shortcut i can use to display the image along with the other text as part of a question. Here is the code for the function that works fine if it is text only:
function populate(){
if(quiz.isEnded()){
showScores();
}
else{
//show question and try to put the picture here
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
//Show Choices
var choices = quiz.getQuestionIndex().choices;
for (var i=0; i< choices.length; i++){
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn"+ i, choices[i]);
}
showProgress();
}
};
};
try this:
element.innerHTML = ('<img src='+choices[linkPosition]+'>');
element.innerHTML += choices[restOfContentLocation];
Or however/wherever you store the image path. I'm a bit unsure of where the problem is but try this.
I have been practicing my Vanilla Js/jQuery skills today by throwing together a newsfeed app using the news-api.
I have included a link to a jsfiddle of my code here. However, I have removed my API key.
On first load of the page, when the user clicks on an image for a media outlet, e.g. 'techcrunch', using an addEventListener, I pass the image's id attribute to the API end point 'https://newsapi.org/v1/articles' and run a GET request which then proceeds to create div elements with the news articles content.
However, after clicking 1 image, I cannot get the content to reload unless I reload the whole page manually or with location.reload().
On clicking another image the new GET request is running and returning results, as I am console logging the results.
I am looking for some general guidance on how to get the page content to reload with each new GET request.
Any help would be greatly appreciated.
Many thanks for your time.
Api convention:
e.g https://newsapi.org/v1/articles?source=techcrunch&apiKey=APIKEYHERE
EventListener:
sourceIMG.addEventListener('click', function() {
$.get('https://newsapi.org/v1/articles?source=' + this.id + '&sortBy=latest&apiKey=APIKEYHERE', function(data, status) {
console.log(data);
latestArticles = data.articles;
for (i = 0; i < latestArticles.length; i++) {
//New Article
var newArticle = document.createElement("DIV");
newArticle.id = "article";
newArticle.className += "article";
//Title
//Create an h1 Element
var header = document.createElement("H1");
//Create the text entry for the H1
var title = document.createTextNode(latestArticles[i].title);
//Append the text to the h1 Element
header.appendChild(title);
//Append the h1 element to the Div 'article'
newArticle.appendChild(header);
//Author
var para = document.createElement("P");
var author = document.createTextNode(latestArticles[i].author);
para.appendChild(author);
newArticle.appendChild(para);
//Description
var description = document.createElement("H4");
var desc = document.createTextNode(latestArticles[i].description);
description.appendChild(desc);
newArticle.appendChild(description);
//Image
var image = document.createElement("IMG");
image.src = latestArticles[i].urlToImage;
image.className += "articleImg";
newArticle.appendChild(image);
//Url link
//Create a href element
var a = document.createElement('a');
var link = document.createElement('p');
var innerLink = document.createTextNode('Read the full story ');
link.appendChild(innerLink);
a.setAttribute("href", latestArticles[i].url);
a.innerHTML = "here.";
link.appendChild(a);
newArticle.appendChild(link);
//Append the Div 'article' to the outer div 'articles'
document.getElementById("articles").appendChild(newArticle);
}
});
}, false);
I tried your fiddle using an api key. It is working for me in that content new content is appended to the previous content in the #articles div. If I'm understanding your question, when a news service image is clicked you would like for only that news service's articles to show. To do that you would need to clear the contents of #articles before appending new content.
To do that with plain js you could use the following above your for loop:
// Removing all children from an element
var articlesDiv = document.getElementById("articles");
while (articlesDiv.firstChild) {
articlesDiv.removeChild(articlesDiv.firstChild);
}
for (i = 0; i < latestArticles.length; i++) {...
Full disclosure, I added the variable name 'articlesDiv' but otherwise the above snippet came from https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
I am making an addon for firefox. I want to extract a video from a HTML page and display it on a black background. Here is what i've got.
//main.js
var pageMod = require("page-mod");
pageMod.add(new pageMod.PageMod({
include: "http://myserver.fr/*",
contentStyleFile: data.url("modify.css"),
contentScriptFile: data.url('hack.js'),
contentScriptWhen: 'start'
}));
//hack.js
video = document.body.innerHTML;
document.body.innerHTML = '';
video = video.substring(video.lastIndexOf("<object"),video.lastIndexOf("</object>"));
video = "<div id='fond'></div><div id='mavideo'>"+video+"</div>"
document.body.innerHTML = video;
document.body.style.backgroundColor = "black";
document.body.style.margin = "0";
My code works but the probleme is that I have to wait "for hours" while the other javascript is beeing executed. I've tried to use contentScriptWhen: 'start' but i dosent change a thing.
Any idea to block the other script of the page ?
Blocking scripts from loading is going to be a little difficult, we can quickly remove them instead.
// remove all scripts
var scripts = document.getElementsByTagName("script");
var parent = null;
for (var i = 0; i < scripts.length; i += 1) {
parent = scripts.item(i).parentNode;
parent.removeChild(scripts.item(i));
}
This code tries to remove all the script tags from your page which would stop the loading of any scripts and allows you to run the rest of your code. Put this at the top of your hack.js script.
I don't know the page you're looking at so it's hard to know what else is going on but your use of substring, and lastIndexOf aren't going to be very fast at all either. We can get rid of those and see if you get any noticible speed increase.
Try using query selectors and Document Fragments instead. Here's an example:
//hack.js
var fragment = document.createDocumentFragment();
var objects = document.getElementsByTagName("object");
// create your div objects and append to the fragment
var fond = document.createElement("div");
fond.setAttribute("id", "fond");
fragment.appendChild(fond);
var mavideo = document.createElement("div");
mavideo.setAttribute("id", "mavideo");
fragment.appendChild(mavideo);
// append all <object> tags to your video div
for (var i = 0; i < objects.length; i += 1) {
mavideo.appendChild(objects.item(i));
}
// clear and append it all in
document.body.innerHTML = '';
document.body.appendChild(fragment);
That code throws all the objects into a document fragment so you can wipe the whole page away and then append it all back in; no libraries required. Your divs fond & mavideo are in there as well.
I didn't really test all this code out so hopefully it works as expected.
We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}