Using javascript variable on html <a> - javascript

I have this javascript code:
<script ="text/javascript">
var newUrl=window.location.href;
var pathArray="";
pathArray=newUrl.substr(newUrl.lastIndexOf("?")+1);
</script>
I want to use the pathArray variable as a part of my href on the tag
This is my html code
<a href="game.html?"+pathArray>
<img src="img/RestartButton.png" style="position:absolute;
left:80px; top:220px">
</a>
but it seems like it doesn't read the value if the variable, but the name of it instead.

You're mixing your javascript into your HTML.
I believe your pathArray variable will also not contain what you are expecting.
Try this in your script tag:
var gamePath = "game.html?" + window.location.search.replace( "?", "" );
document.getElementById("gameAnchor").setAttribute("href", gamePath);
And add an id to your anchor:
<a href="#" id='gameAnchor'>
The javascript will get all GET parameters from the current url and then replace the href attribute in the element with an id of gameAnchor with your game.html concatenated with the GET parameters in the url.

You will have to use JavaScript for this as well. First give your anchor an ID:
<a id="myLink" href="game.html?"><img src="img/RestartButton.png" style="position:absolute; left:80px; top:220px"></a>
And then add following to your JavaScript code:
document.getElementById('myLink').href += pathArray;
The code will add the content of your string variable to href property of anchor element.

First, make the anchor easier to select by giving it an identifier.
(This is assuming there is more than one anchor on your page)
Then, in your script above include:
var anchor = document.getElementById("pathLink");
The anchor tag has a native href property, so assigning the new one is as easy as this:
Rewrite:
var anchor = document.getElementById("pathLink").href += pathArray;

It won't work like that. You will have to loop through the anchors your need using JavaScript.
This hasn't been tested. I'm assuming you want this to happen to more than one anchor link.
HTML:
<a class="updatethis" href="game.html">...</a>
...
<a class="udpatethis" href="game.html">...</a>
JavaScript:
var anchors = document.getElementsByTagName('a');
for (var i = 0, a; a = anchors[i++]; ) {
if (a.className === 'updatethis') {
a.href += window.location.search;
}
}

You can't place a javascript variable anywhere in html.
Instead you need to get the dom element through script and append the href attribute.
give your anchor an id or classname and try this as an example.
<a id="myLink" href="game.html">
<img src="img/RestartButton.png" style="position:absolute;left:80px; top:220px">
</a>
<script type="text/javascript">;
document.getElementById('myLink').href += window.location.search
</script>

You can access an attribute of an element in HTML. Although it's not really an HTML variable, it's roughly close to it. As you expect from a variable, you can get, set and remove it.
Element.getAttribute() :
getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details : https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
Example :
let myDiv = document.getElementById("myDiv");
console.log(myDiv.getAttribute("variable"))
<div class="div" id="myDiv" variable='test'</div>
Of course, you can set, or remove an attribute too :
Element.setAttribute()
Sets the value of an attribute on the specified element. If the
attribute already exists, the value is updated; otherwise a new
attribute is added with the specified name and value.
Element.removeAttribute()
Blockquote
removeAttribute removes an attribute from the specified element.
Note:
This being said, you will need javascript to interact with attributes. And that explains partially why it's not a "proper variable".

Think of using some template engine as undescore, moustache or doT.js. you can easily substitute html identifier or part of with template's data variables.

Related

Why will the colour of the active link not highlight blue? [duplicate]

I have an anchor tag that has a local href value, and a JavaScript function that uses the href value but directs it to a slightly different place than it would normally go. The tag looks like
<a onclick="return follow(this);" href="sec/IF00.html"></a>
and a JavaScript function that looks like
baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
location.href = baseURL + item.href;
}
I would expect that item.href would just return a short string of "sec/IF00.html", but instead it returns the full href, "http://www.thecurrentdomain.com/sec/IF00.html". Is there a way that I can pull out just the short href as put in the anchor <a> tag? Or do I lose that by natural HTML behavior?
I suppose I could use a string manipulation to do this, but it gets tricky because my local page may actually be "http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html", and my href field may or may not have a subdirectory in it (for ex href="page.html" vs. href="sub/page.html"), so I cannot always just remove every thing before the last slash.
You may wonder why I am requesting this, and it is because it will just make the page a lot cleaner. If it is not possible to get just the short href (as put in the anchor <a> tag), then I could probably just insert an extra field into the tag, like link="sec/IF00.html", but again, that would be a little messier.
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
document.getElementById("link").getAttribute("href");
If you have more than one <a> tag, for example:
<ul>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
You can do it like this: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags, or depends on the condition you make.
This code works for me to get all links of the document
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.
$(".test a").on('click', function(e) {
console.log(e.target.href); // logs https://www.test.com/#test
console.log(e.target.hash); // logs #test
});
The href property sets or returns the value of the href attribute of a link.
var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
var url="https://www.google.com/";
console.log( url+hello);
document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html

generate href for a link based on id using javascript

I'm trying to use JavaScript to create an ID for my links and also to tell it where to link to.
My JavaScript has generated a link element in my HTML:
<a id = "NB4-CAXL-14U-12-AAG"> Link Text </a>
And that appears as it should.
I then have a variable eopartnum[i]:
console.log(eopartnum[i]); //output: NB4-CAXL-14U-12-AAG
This variable matches my ID for my link above. Then i tried to access that link via the ID and assign an href to it, like so:
var linktoprod = document.getElementById(eopartnum[i]);
console.log(linktoprod); //returns null
linktoprod.href = "http://www.enviroptics.com/"; //Cannot set property 'href' of null(…)
Why does my linktoprod come up as null? Is my syntax wrong?
JSfiddle for full code: http://jsfiddle.net/98oL12tk/17/ Lines 106-109 in JS section.
The problem is that you are calling getElementById() before you append the table to the document. At the time that you are querying for the ID, it doesn't yet exist. This example seems a bit contrived; I think you could just set firstcelllink.href = 'http://www.enviroptics.com/';
EDIT: probably more appropriate to use firstcelllink.setAttribute('href', 'http://www.enviroptics.com/');

Changing asp.net core TagHelpers with Javascript

I have
<a id="continue-link" asp-controller="Account" asp-action="Register" asp-route-id="1">Continue </a>
in my asp.net core application, that generate this html when compiled:
Continue
How can i change asp-route-id value from javascript? I tried with $().attr but it's not recognized.
You have to change your href attribute in generated html.
You can achive this by geting your href attribute, split it into array, then change value in array and join it again into one string with separator and then replace href attribute in your a element.
Code example:
var $link = $('#continue-link');
var href = $link.attr('href').split('/');
href[3] = 4; //here you set your new asp-route-id value
$link.attr('href', href.join('/'));
Check this codepen to see how it work.

Setting a JS variable and using it in html tag

I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, this is the code:
<script>
var randomnumber=Math.floor(Math.random()*11)
</script>
<div id="<script type="text/javascript">document.write(randomnumber)</script>"></div>
Thanks.
Edit: I just used a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?
Use
<script>
document.write('<div id="'+randomnumber+'" ></div>');
</script>
You can't open a script tag inside an attribute
Or you can create it using JS:
var randomnumber=Math.floor(Math.random()*11);
a = document.createElement('div');
a.setAttribute('id',randomnumber);
document.body.appendChild(a);
// if you know the exact class or ID where it is to be appended you can use
document.getElementsByClassName("myclass")[0].insertBefore(a, document.getElementsByClassName("beforeClass").firstChild);
This will create a div, with the id as the randomnumber and append it to the body

Replace anchor tag onclick javascript function parameter

I have a page which has a couple of anchor tags in this format:
<a onclick="javascript:RefreshPageTo(event, "/web/Lists/exceptionlog/AllItems.aspx?Paged=TRUE&PagedPrev=TRUE&p_Created=20111026%2017%3a30%3a16&p_ID=175\u0026PageFirstRow=1\u0026\u0026View={8AB948D3-7F13-4331-9F06-29C8480B1E80}");javascript:return false;" href="javascript:">
If you look at the RefreshPageTo javascript function it has a couple of arguments. The second argument is a server relative url. It has some querystrings, I need to append some more query strings to it.
Lets say for example I want to append the following query string to it: "FilterColumn=title&FilterValue=th". Any ideas how I would do this using jquery?
Your HTML:
<a data-src="/web/Lists/exceptionlog/AllItems.aspx?Paged=TRUE&PagedPrev=TRUE&p_Created=20111026%2017%3a30%3a16&p_ID=175\u0026PageFirstRow=1\u0026\u0026View={8AB948D3-7F13-4331-9F06-29C8480B1E80}"> </a>
Note that I used 'data-src' instead of 'href' attribute.
when document loaded, run this script:
$('a').click(function(event) {
RefreshPageTo(event, $(this).attr('data-src') + '?FilterColumn=title&FilterValue=th');
/* concat what ever you want */
return false;
}

Categories