How to put JavaScript value inside HTML ?
I am trying to put JavaScript value inside HTML like below.
<p>
Check your Credit Score Here
</p>
To achieve the results, you can make use of document.getElementById('').href property:
HTML (added the id attribute to the <a> tag):
<p>
Check your Credit Score <a id="link" href="" target="_blank">Here</a>
</p>
JavaScript:
window.onload = function() {
var first_name = 'Peter';
document.getElementById('link').href = 'http://someaddress.com?first_name='+ first_name;
// debug your results
console.log(document.getElementById('link').href);
}
Here is the JSFiddle
do this if you want to change the link
document.querySelector('a').href = "http://someaddress.com?first_name=" + first_name;
You can do like this
<p>
Check your Credit Score
<a href="http://someaddress.com?first_name='+ first_name +'" target="_blank"
>Here</a >
</p>
<script type="text/javascript">
const a = document.querySelector('a');
const first_name = 'John';
a.href = 'http://someaddress.com?first_name=' + first_name ;
</script>
For best practice do an if check otherwise your selector might not be found in the dom.
Also, if in querySelector("...anything...") not querySelector("a") is given the editor won't suggest the href prop that exists or not. Hence, setAttribute makes more sense.
const URL = "http://someaddress.com?first_name="
const name = 'adiat'
const anchor = document.querySelector(".what-ever")
if(anchor){
anchor.setAttribute("href", `${URL}${name}`);
}else{
console.warn("element not found to replace href attribute")
}
// shorthand -> anchor?.setAttribute("href", `${URL}${name}`);
A robust way would be to use a token to replace, I've used {{FirstName}}. Use an attribute selector to select via that token then replace that token on the href attribute
let firstNameLinks = document.querySelectorAll("a[href*='{{FirstName}}'");
let firstName = "Bob";
for(i = 0; i < firstNameLinks.length; i++){
console.log(firstNameLinks[i].href)
firstNameLinks[i].href = firstNameLinks[i].href.replace("{{FirstName}}", firstName);
}
A link
Another link
Related
create a hyperlink with the variable link
<html>
<body>
<center><h1> retrive data</h1></center>
<h1 id="head1"> </h1>
<input type="text" placeholder="enter your unique id" id="pass"/>
<input type = "button" value = "submit" id="but" onclick="myfunction();"/>
<script>
var pass;
function myfunction()
{
pass = document.getElementById("pass").value;
document.writeln(pass);
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
var passwordToLookFor = pass;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once("value").then(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
var link = child.val().user_name;
document.writeln(link);
});
});
}
</script>
</body></html>
i want to create the value of link as a hyperlink
i want the hyperlink to be created once when the function is called
Are you just looking for how to make it an anchor tag?
<script>
var pass;
function myfunction()
{
...
var link = child.val().user_name;
document.writeln("<a href='"+link+"' target='_blank'>"+link+"</a>");
});
});
}
</script>
</body></html>
You can create an a dom element like this:
let link_el = document.createElement('a')
link_el.href = link // assuming link holds the value of the href you want
Then insert it into the dom wherever you want.
If I understand correctly and the link variable contains the actual address you want to navigate to, then this will work. First simply set an ID on the div you want to populate with links:
<div id="target-div"></div>
Then populate it like so (I just created an array for demo purposes, but this would be your snapshot.forEach:
var links = ['link1', 'link2', 'link3']
var targetDiv = document.getElementById("target-div");
links.forEach(function(link) {
var anchor = document.createElement('a');
anchor.href = link;
anchor.innerText = link;
targetDiv.appendChild(anchor);
var br = document.createElement('br');
targetDiv.appendChild(br);
});
Demo: https://jsfiddle.net/csnuh7rd/2/
How can I display a href link inside an if condition using javascript?
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var x = document.getElementById("fname");
if(x.value.indexOf("aaaa")>=0)document.getElementById("result").innerHTML= ""+ x.value + "" ;
else document.getElementById("result").innerHTML=x.value;
}
</script>
<form method="post" action="esegui.php">
Name<br><input type="text" id="fname" onkeyup="myFunction()">
</form>
<p id="result"></p>
</body>
</html>
You can create anchor tag using JavaScript following way:
var aTag = document.createElement('a');
aTag.setAttribute('href',"http://www.google.com");
aTag.innerHTML = "aaa";
document.body.appendChild(aTag);
Put above code in if condition will create anchor tag(link).
Although your question is a little bit confusing, I'll try to help you
If what you want is to create a specific link, do this:
var link = window.document.createElement("a");
var str = window.document.getElementById("theidofyourinput").value;
link.textContent = str;
link.href = 'http://www.linkofyourpage';
document.getElementsByTagName('body')[0].appendChild(link);
Try researching the createElement() method in JavaScript, calling it to create an anchor element in the body of your if statement e.g.
var myLink = document.createElement('a');
myLink.appendChild(document.createTextNode('link name')); //visible text
myLink.setAttribute('href', 'http://google.com'); //link href attribute
document.getElementById('someId').appendChild(myLink); //append the element
There are many ways to do this but you have not mentioned specific scenario so do like this:
In HTML:
<div id="test"></div>
In Java script:
var markup = "link";
var v = document.getElementById("test") ;
v.innerHtml(v );
In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick
Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);
As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example
<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle
First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.
Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick
Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/
<li class="catalog-list-item" data-icon="false">
<a href="/items/170893265">
How would I use console.log to log the href /items/IDHERE (IDHERE = 170893265) by using catalog-list-item?
$.get("http://m.roblox.com/Catalog/CatalogSearch?startRow=0&keyword=&filter=Collectibles",
function(Data) {
var test = $(Data).find('.catalog-list-item')
var itemID = test.attr("href");
console.log(itemID);
});
And that won't work for me (the test part does work, not the itemID part though.)
If
<li class="catalog-list-item" data-icon="false">
<a href="/items/170893265">
is the full response, then li.catalog-list-item will be the selected element in $(Data). I.e. $(Data).find('.catalog-list-item') would try to find a .catalog-list-item element inside a .catalog-list-item element, which doesn't work.
You can .filter the selection and then search for the a element(s):
var test = $(Data).filter('.catalog-list-item').find('a');
You left out the a tag, which is the one you're targeting -- the one that has the href attribute you're looking for:
var test = $(Data).find('a'); //<<<<-------
var itemID = test.attr("href");
console.log(itemID);
To get just the id use:
var itemID = test.attr("href").split('/').pop();
you realize the href attribute isn't in the li tag. I suggest you do this
var test = $(Data).find('.catalog-list-item')
var itemID = test.find('a').attr("href")
console.log(itemID)
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product