Get dynamically created names of dynamical links - javascript

I need to create a link for a set of documents. They are created dynamically, thus the names are also different, f.ex. Test, Test2, so one.
I need to show the link like "Document TestN", where links changed according to the current document. I can now create the links by a href="id" onklick=bla+bla+bla", but the name does not change. Instead of 'Dashboard' I need to get 'Dashboard of "ConcreteSite"', where I can get names by pageHeader:
document.getElementById("pageHeading").appendChild(pageHeading);
<script language="javascript" type="text/javascript">
var siteNameAsParam = window.location.search;
var scrt_var = siteNameAsParam.split("siteName=")[1];
</script>
<p>You are here: Dashboard </p>

Based on your code I think this is what you're after but more detail on what you're trying to do would be great.
<p>You are here: Dashboard </p>
<p>You are here: Dashboard </p>
<script>
document.addEventListener('DOMContentLoaded', function(event) {
var links = document.getElementsByTagName("a");
for (i = 0; i < links.length; i++) {
var siteNameAsParam = window.location.search;
var scrt_var = siteNameAsParam.split("siteName=")[1];
links[i].href = links[i].href + '?siteName=' + scrt_var;
links[i].innerText += ' fred';
}
}, false);
</script>
This does the following:
On page load gets all links on the page
loops through the links and grabs the query strings from the url
splits the query string on siteName
sets each link url to add the query string
updates the links text to append the query string (or undefined if it doesn't exist (see note below)
Note: your code implies you already have a query string in the url of siteName=SITENAMEHERE. Also, depending what you're trying to achieve, there are probably much better approaches. This I hope answers your current question but I think you should review how other achieve what you're after.
Update:
Here is a jsfiddle with a different working sample of what I think you might want. Hopefully it helps. there are comments in the fiddle. I think you want to try doing more when the link is created (set the event listener there, update the text as desired, etc.) instead of on the click event.

Related

How to get a word content from an element and append it to the end of a URL of a href?

There is a function called "dictionary link" in Anki as the manual explains:
Dictionary Links
You can also use field replacement to create dictionary links.
Imagine you’re studying a language and your favourite online dictionary allows you to search for text using a web URL like:
http://example.com/search?q=myword
You could add an automatic link by doing the following in your template:
{{myword}}
check in dictionary
The template above would allow you to search for each note’s expression by clicking on the link while reviewing.
I am now learning HTML + CSS + Javascript from scratch, I'd like to add a similar tool in my own practice website.
I want to copy the text content (the word that I want to check in the dictionary) of an element, add it to the end of the url. When I click the link the corresponding dictionary page will show up.
For example:
<span id="search">entry</span>
copy "entry" and add it to the end of
<a id="dictionary" href="http://example.com/search?q=">link</a>
Since I am a complete beginner, I haven't learned jQuery or other tools yet. Is it possible to do this only by HTML and Javascript?
const search = document.getElementById("search");
const link = document.getElementById("dictionary");
link.href = `http://example.com/search?q=${search.innerText}`;
You have to assing new href property to link by getting innerText of search element
Did you try to use these apex:
<a href=`http://example.com/search?q=${myword}`>check in dictionary</a>
Otherwise you have to build the link by js script and then assign to a element:
let link = 'http://example.com/search?q=' + customParam
// Fetch the tag <a>
let hrefElement = document.getElementById('#idElement');
// Change the href param with your link
hrefElement.href = link;
Try this link and try to work around
function clicks(){
var foo = document.getElementById("dictionary").id
$("a").attr("href", "http://example.com/"+foo+"?q=")
}
document.getElementById("myLink").href = customLink will set your link to your a element
//get input element
var inputElement = document.getElementById('param-input');
// add event to listen every time a letter is introduced
inputElement.addEventListener("keyup", composeUrl);
function composeUrl() {
// get value from input
var param = inputElement.value;
// compose url
var customLink = "http://example.com/search?q=" + param
//set href
document.getElementById("myLink").href = customLink
//get href
var result = document.getElementById("myLink").href;
//print link in a div
document.getElementById("demoLink").innerHTML = result.toString()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="param-input" />
<a id="myLink" />
<div id="demoLink"> url composed </div>

Using regexes to modify the text of html (with javascript)

I want to modify the text in a html file using javascript in an android webview.
Essentially, I want to do what android Linkify does to text, but I don't want to do it with java code, because I feel like that might delay the webview rendering the html (if I parse the text before sending it to the webview).
So, for example a piece of html like this:
<html>
<body>
google.com <!--these two shouldn't be linked-->
akhilcherian#gmail.com <!--these two shouldn't be linked-->
<p>www.google.com</p> <!--this should be linked-->
<p>102-232-2312 2032-122-332 </p><!-- should be linked as numbers-->
</body>
</html>
Should become this:
<html>
<body>
google.com
akhilcherian#gmail.com
<p>www.google.com</p>
<p>102-232-2312 <a href="tel:2032-122-332>2032-122-332</a> </p>
</body>
</html>
I already have the regexes to convert numbers and email ids to links, and they're working well enough. What I want to ensure is that I don't link anything that's already within tags. I've removed anchor tags, so they're not an issue, but I also need to avoid linking things like this:
<div width="1000"> <!-- Don't want this '1000' to be linked (but I do want other 4 digit numbers to be)-->
So for example if my regex for links is:
var replacePattern1 = /((https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim
How do I make sure that it's not within < and >? (Answers using javascript would be appreciated, but if you feel like this is a stupid way of doing it, please let me know about alternatives).
If you're answering with javascript, this question can essentially be shortened to:
How do I write a regex in javascript to search for patterns which are not surrounded by '<' '>' tags
So if you use JS than mean is client side, your DOM page have free access of all objects of your page coef events.
May be in this step you dont need to use a regex just using DOM.
jquery lib can easy update DOM object.
in your step you want only tag.
So i suggest :
//using jquery
$("p").each(function(){
console.log($(this))
});
//js
var paras = document.getElementsByTagName("p");
for(p in paras){
console.log(paras[p])
}
As i tell you the deal is manipulate the DOM so example with you step dunno if exactly what you try to get :
var paras = document.getElementsByTagName("p");
var hrefs = [];
//what you want to replace in the loop of p
var json_urls = {"links":["http://", "tel:"]};
for(p in paras){
//copy of text content of your p
var text_cp = paras[p].textContent;
//delete the p[i] content
paras[p].textContent = "";
//create element dom a
hrefs[p] = document.createElement("a");
//i add attribute id with some affectation unique
hrefs[p].id = "_" + p;
//add attribute href to a with some affectation replace + content
hrefs[p].href = json_urls.links[p] + text_cp;
hrefs[p].textContent = text_cp;
paras[p].appendChild(hrefs[p]);
}

getElementById from another page

I am trying to get one div from one webpage URL to another webpage and display in plain text using getElementById without using AJAX or jQuery because I'm going to implement it in FitNesse. Is there a way to pass the URL?
You could load the URL in a hidden iframe.
Then use iframe.contentWindow.document.getElementById($id) as outlined here: How to pick element inside iframe using document.getElementById
Something along the lines of:
<iframe src="urlWithinYourDomain.html" style="display:none"></iframe>
Followed by a function something like:
var divElement = document.getElementById('iframeId').contentWindow.document.getElementById('elementIdOnSourcePage');
document.getElementById('targetParentId').appendChild(divElement);
I'm afraid I can't test this at the moment, so there may be syntax errors, but I think it conveys the idea. It's a bit of a dirty approach, but given your constraints it's the best way I can see to do what you're asking.
On page 1.
<div id="dataDiv">1234</div>
<a id="getData" href="">Page2</a>
<script>
var data = document.getElementById('dataDiv').innerHTML;
//This will get the content from the div above with the id of "dataDiv"
document.getElementById("getData").setAttribute("href","page2.html?var="+data);
//This will set the url of the anchor with the id of "getData" with your url and the passing data.
</script>
And on page 2
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var var1 = getUrlVars()["var"];
This will send the content in your div on page one to page two. the result url on page 1 will be page2.html?var=1234

Tampermonkey - add page using non-existing URL

I'm creating a userscript which adds new functions to a website.
The website has many users, but doesn't have a feature to search for users.I want to create such a function. To do that, I have created a button in the already existing search page for other search purposes. When I click the button, I need the script to search for the input on Google and fetch the URLs and show the results in a piece of HTML code on a non-existing page.
Can I fake an URL with a userscript, so that it uses it to show HTML?
If not, can I replace certain HTML within the page?
The code isn't really that interesting. It just adds a button with a link and selects it when on the non-existing page.
CODE:
if (document.URL == "http://www.bierdopje.com/search" || document.URL == "http://www.bierdopje.com/search/" || window.location.href.indexOf("search/shows") > -1 || window.location.href.indexOf("search/episodes") > -1 || window.location.href.indexOf("search/forum") > -1) {
var users = document.createElement('li');
users.setAttribute('class', 'strong');
var UsersNode = document.createTextNode("Gebruikers");
var UsersLink = document.createElement('a');
UsersLink.setAttribute('href', 'http://www.bierdopje.com/search/users/');
document.getElementById("submenu").childNodes[1].appendChild(users).appendChild(UsersLink).appendChild(UsersNode);
if (window.location.href.indexOf("search/users/") > -1) {
UsersLink.setAttribute('href', './');
UsersLink.setAttribute('class', 'selected');
}
}
Sorry for answering my own question, but like Brock Adams already said: it may have been too localized.
The solution to fake an url is to replace the 404 not found content.
If there's like a container with a header and a paragraph, find the container by making it a variable, and then replace it with another variable:
// find the container
var example = document.getElementById('container').childNodes[0];
// set new container
var newcontainer = document.createElement('div');
newcontainer.setAttribute('id', 'ncontainer');
// replace the existing container with the new one
example.parentNode.replaceChild(replacement, example);
// write content to the new container
document.getElementById('ncontainer').innerHTML ='<p>This is not a 404 anymore</p>';
There are probably a lot more and shorter ways to accomplish this, but they can be found by Google (javascript replace).
To replace the complete page, use
document.write()
To finish the page, you can set the title with the following:
document.title = "WEBSITE TITLE";

How can I add "href" attribute to a link dynamically using JavaScript?

How can I add the href attribute to a link dynamically using JavaScript?
I basically want to add a href attribute to <a></a> dynamically (i.e. when the user clicks on specific image in the website).
So from:
<a>Link</a>
I need to go to:
Link
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).
To add any attribute, just use the setAttribute method on the DOM object:
a = document.getElementById(...);
a.setAttribute("href", "somelink url");
document.getElementById('link-id').href = "new-href";
I know this is an old post, but here's a one-liner that might be more suitable for some folks.
First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.
Then, add something like this in the javascript function that you're calling:
var abc = 'somelink';
document.getElementById('test').innerHTML = 'Link';
This way the link will look like this:
Link
More actual solution:
<a id="someId">Link</a>
const a = document.querySelector('#someId');
a.href = 'url';
I know there seems plenty good answers here, but none of them seemed simple enough for what I was "told" to do in the 2022 Udemy Web Development Bootcamp by Angela.
So I remembered how simple the use of scriplets was and figured to try it and it works just as well.
For those like me who are learning let me explain:
. - takes you to current URL
then static path
then dynamic variable generated for each post (its a blog website)
Read More
This is using JS inside an EJS page
same solution is also given in the solution lecture of the bootcamp here:
https://www.udemy.com/course/the-complete-web-development-bootcamp/learn/lecture/12385596#overview
Lecture 317
I came here because I wanted to dynamically set the link href after it's been clicked
<a id='dynamic'>link text</a>
document.getElementById("dynamic").addEventListener("click", onClick_dynamic)
function onClick_dynamic(e){
const nextPage = getNextPage()
document.getElementById("dynamic").href = _BASE_URL + "?nextPage=" + nextPage
// e.default processing sends user to href
}
Single line solution
<a id="yourId">Link</a>
document.querySelector("#yourId").href("URL")
enter code here javasicript added
var x = "www.google.com";
vay y = "550";
var z= x+y;
document.write('GONDER');

Categories

Resources