I want to use a hyperlink string in HTML page which I want to declare source link (URL) in my js file. Please tell me how can I call that URL from my js into html.
Thanks
There are a number of different ways to do this. You could use document.createElement() to create a link element, and then inject the element into the DOM. Or you could use the .innerHTML property of an element that you already have on the page to insert the link using text. Or you could modify the "href" attribute of an existing link on the page. All of these are possibilities. Here is one example:
Creating/Inserting DOM Nodes with DOM Methods
var link = document.createElement('a');
link.textContent = 'Link Title';
link.href = 'http://your.domain.tld/some/path';
document.getElementById('where_to_insert').appendChild(link);
Assuming you have something like this in your HTML:
<span id="where_to_insert"></span>
Creating/Inserting DOM Content with innerHTML
And another example using innerHTML (which you should generally avoid using for security reasons, but which is valid to use in cases where you completely control the HTML being injected):
var where = document.getElementById('where_to_insert');
where.innerHTML = 'Link Title';
Updating the Attributes of a Named DOM Node
Lastly, there is the method that merely updates the href attribute of an existing link:
document.getElementById('link_to_update').href = 'http://your.domain.tld/path';
... this assumes you have something like the following in your HTML:
<a id="link_to_update" href="javascript:void(0)">Link Title</a>
Try this:
var alink = document.createElement("a");
alink.href = "http://www.google.com";
alink.text = "Test Link";
document.getElementsByTagName("body")[0].appendChild(alink)
From whatever I understand, You want to update href with JS variable.
You can use Jquery to achieve it.
try $("a").attr("href", js_variable)
Refer this for more details
How to change the href for a hyperlink using jQuery
It seems like you would be able to do something like this:
Using Javascript.
var col2= document.getElementById('id_Of_Control');
col2.innerHTML="<a href='page2.html?" + params + "'>Page 2</a>";
where col2 is another container control something like div,span, or any.
Using jQuery.
Here I will recommend you to Use jQuery. So you can be more dynamic.
$("#col2").append("Page 2");
OR
$("#col2").after("Page 2");
OR
$("#col2").before("Page 2");
Related
I have a title tag that looks something like this:
<title>My Page Title - Photo #3</title>
I want to use JavaScript to change the numeric part of it, without having to hard code the "My Page Title - Photo #" string which is generated server side.
I tried wrapping the number in a span so that I could change the contents of the span:
<title>My Page Title - Photo #<span class="photoid">3</span></title>
But it seems HTML is not allowed in the title tag. I'd really like to pursue the class approach if possible as that would allow me to use a line of jquery such as this:
$('.photoid').html(new_photoid);
Did I mention that the photoid appears in several places on the page, which is why I want to be able to use this oneliner to change them all at the same time? For example:
<p>A paragraph also containing the number <span class="photoid">3</span></p>
A title can only have text, so you need to parse it out.
document.title = document.title.replace(/\d+$/, "new value");
title can't be set like that,
it's not a child of .html
some thing like
var num = 3;
document.title = "foo "+num
to set the title, then reuse num for these photoids.
Use the jQuery onDocumentReady syntax:
$(function () {
var elements = $('.contains_photoid');
elements.html(elements.html().replace("3", "4"));
$(document).attr('title', $(document).attr('title').replace("3", "4"));
});
You can't see the title change in this example, but that is the syntax. See Changing the page title with Jquery
The "3" and "4" can be changed to anything, so you can create the page with a unique character string in place of the real ID in order to easily replace it if it appears in text with numbers already in it.
http://jsfiddle.net/ZmXj5/1/
Javascript
var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;
See this fiddle for proof: http://jsfiddle.net/xrkhA/
(I used a div content because you can't use title in jsfiddle)
You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');
How can I get link text using jQuery?
My link is:
google site
I need to get "google site" using jQuery.
That is the text shown to the user in UI not the name. To get that you use a jQuery's text method.
Use the .text() method as
$('a').text();
Even you can use a variable to get the value to, for example:
var hyperLinkText = $('a').text(); // get the name
$('element').html(hyperLinkText); // write it somewhere
If you means the href value of your anchor, then you can use .attr():
var href = $('#id1').attr('href');
or .prop():
var href = $('#id1').prop('href');
If you want to get the text inside anchor, you can use .text():
var text = $('#id1').text();
you can try with this:
var linkText=$('#id1').text();
I am trying to add a link to a page I cannot directly access the HTML on, aside from the footer. Using Javascript, I am attempting to use the createElement() method. I have successfully used the same process to create a link element in the header.
function createForgotPasswordLink(){
var pwlink=document.createElement("a")
pwlink.setAttribute("id", "forgotPssLink")
pwlink.setAttribute("href", "http://www.mysite.com/page.aspx")
pwlink.innerHTML("Forgot Password?")
document.getElementsByTagName("body")[0].appendChild(pwlink)
}
createForgotPasswordLink();
The only difference between the two scripts is that when making the link element, I appendChild() on the head not body and I do not set the innerHTML of the link element as I have done in the above a element. For some reason, the above code does not work. Even after removing line 5.
You are using the property .innerHTML like a method. Don't use parens, use an =. Also, I wouldn't bother setting the attributes, just set the property values directly. The code is more straightforward and easier to read:
function createForgotPasswordLink() {
var pwlink = document.createElement("a");
pwlink.id = "forgotPssLink";
pwlink.href = "http://www.mysite.com/page.aspx";
pwlink.innerHTML = "Forgot Password?";
document.body.appendChild(pwlink)
}
Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method
I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links. It seemed to me that the way to do that would be to match the contents of href against /^https?:///.
But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http". That is, if the HTML contains:
<a id="rel" href="/relative/link">inner</a>
accessing
document.getElementById("rel").href
returns
http://example.com/relative/link
How can I access the raw data in the href attribute?
Alternately, is there a better way to find relative links?
Try the getAttribute method instead.
Typical. I figured it out myself almost immediately after posting the question.
instead of:
anchor.href
use:
anchor.getAttribute("href")
Of course, it took me longer to type in this answer than it took everyone else to answer it. (Damn, you people are fast.)
Here's a code snippet you could run to test.
const anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let hrefFullPath = anchor.href;
let hrefRelativePath = anchor.attributes.href.value;
console.log('hrefFullPath', hrefFullPath);
console.log('hrefRelativePath', hrefRelativePath);
}
Let's say, you are at http://localhost:4200, and this is your document as you have shown in the question.
<a id="rel" href="/relative/link">inner</a>
This anchor's attribute value of href is:
document.getElementById('rel').attributes.href.value => /relative/link
And anchor's href value is:
document.getElementById('rel').href => http://localhost:4200/relative/link
I hope it helps.
Get the link dom and add attributes for same and append the actual link to same.
var hrefUrl = 'https://www.google.com/';
const link: HTMLLinkElement = dom?.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('id', 'seo');
dom?.head?.appendChild(link);
dom?.getElementById('seo')?.setAttribute('href', hrefUrl);
// working
Hope this will work for dynamic links that to append for each dynamic pages under js / ts.