add a variable in href using javascript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am new in javascript i want to add a javascript variable in
i use some javascript like this but it not working
HTML
<ul id="direction"></ul>`
JS
var abc = 'link/';
var cba = 'hello';
document.getElementById('directions').innerHTML = 'Link';`

This code should work, make sure the html id matches the getElementById and use the right quotes as mentioned before.
You want to add a href to a list but you should add a li first, in my example I use a div tag.
var name = 'google';
var ext = '.com';
document.getElementById('direction').innerHTML = 'Link';
A better way to do this would be by using backticks `` < these like so:
var name = 'google';
var ext = '.com';
var link = 'Link';
document.getElementById('direction').innerHTML = `${link}`;

Your code, fixed ID, and quotes:
document.getElementById("direction").innerHTML='Link'
Or maybe better:
var node=document.createElement("A")
node.setAttribute("href","https://"+var1+var2)
document.getElementById("direction").appendChild(node)
I hope that this will help you!

I'd recommend avoiding using innerHTML in most cases! The following accomplishes what you want programmatically without needing to generate HTML strings:
window.onload = () => {
let abc = 'link/';
let cba = 'hello';
let container = document.getElementById('direction');
let link = container.appendChild(document.createElement('a'));
link.setAttribute('href', `https://${abc}${cba}`);
link.appendChild(document.createTextNode('Link'));
};
<ul id="direction"></ul>

Related

Problem adding Js variables in HTML with getElementById [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
<body>
<h1>Operadores aritméticos</h1>
<h3>+ Adición (102+103)=</h3><p id="suma1"></p>
<h3>- Substracción</h3><p id="resta1"></p>
<h3>* Multiplicación</h3><p id="multi1"></p>
<h3>/ División</h3><p id="div1"></p>
<h3>% Módulo</h3><p id="mod1"></p>
<script>
var suma = (102+103);
var resta = (36-20);
var multiplicación = (27*30);
var división = (900/30);
var módulo = (106%3);
document.getElementById("suma1").innerHTML = suma;
document.getElementById("resta1")innerHTML = resta;
document.getElementById("multi1")innerHTML = multiplicación;
document.getElementById("div1")innerHTML = división;
document.getElementById("mod1")innerHTML = módulo;
</script>
Hello guys, I have a problem, im pretty new at this (programming with HTML, Js, etc.).The issue is that when I try to make my Js variables appear on HTML (with document.getElementById), they do not appear. Nevertheless, if erase every document.getElementById except the one containing "suma1", the browser displays me the result of the sum (205), but if I add even one of them, the browser doesn´t display anything.
I hope I was clear with my problem, it seems very simple but hard to explain.
Any suggestions?
Thanks in advance
The reason you're not seeing anything when you add the statements to populate resta1, multi1, div1, and mod1 is probably because they all have a syntax error. This is likely causing even the first statement (suma1, which is syntactically valid) not to work.
Valid Statement
The 1 statement that is working is document.getElementById("suma1").innerHTML = suma;
Invalid statements
All the other statements follow this pattern:
document.getElementById("id")innerHtml = variable;
Note that you're missing the . between getElementById("id") and innerHtml. If you add the missing . then it should all work as expected.

Javascript set href for all elements in class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have a list of (at least 4) < a > tags with the class 'remove-typefilter'
They do not have a 'href' ., but I want to give them all one when the users clicks a button.
This is the JS function I've written to achieve this:
function BuildButtons(urlparams) {
elements = document.getElementsByClassName('remove-typefilter')
for (let element in elements) {
element.href = 'www.newlink.com' + urlparams
element.style = 'color: red;'
}
}
Yet when I run this function it does not change the attributs. The A tags get no link and the styling goes not change.
Does anyone know what I am doing wrong?
Two issues:
Syntax error in the function definition: url-params is invalid. Use urlParams.
for ... in loops iterate the keys of the iterated object, not the values. Use for ... of instead
Also:
Do not define elements as a global variable. Use const.
Better add a protocol in your URL, like http://
Although assigning a string to style works, it is more efficient to assign directly to the relevant style property
Corrected code:
function BuildButtons(urlParams) {
const elements = document.getElementsByClassName('remove-typefilter');
for (const element of elements) {
element.href = 'http://www.newlink.com' + urlParams;
element.style.color = 'red';
}
}
you can set the href attribute by using the
Element.setAttribute(*name*,*value*);
for loops return the index not the actual element.
for (let element in elements) {
should be
for (let i in elements) {
let element = elements[i];
or
elements.forEach(function(element) {
Why not use querySelectorAll() and forEach()
function BuildButtons(urlparams) {
var elements = document.querySelectorAll('.remove-typefilter');
elements.forEach(function(element){
element.href = 'www.newlink.com' + urlparams
element.style = 'color: red;'
});
};
BuildButtons('#xxx'); // invoke call the function how ever you like.
<a class="remove-typefilter">one</a>
<a class="remove-typefilter">two</a>
<a class="remove-typefilter">three</a>

jQuery doesn't give a proper output, but gives these [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
(function() {
var a = document.createElement('a');
var mref = 'http://www.someprivatelink.net';
var linkText = document.createTextNode(title1);
var title1 = $('#node-264152').find('.audio-description').html();
alert(title1);
a.appendChild(linkText);
a.title = title1;
a.href = mref;
document.body.appendChild(a);
})();
I'm using this script to add an download link to the bottem of my page wich doesn't to to be permanent so I enter it via console with Google Chrome.
The ID and the Class are correct to the value I need to extract, I've added the alert to check if the fault was in the HTML or in my javascript.
The output at the bottem of the page has the value of 'Undefined', while it has to be 'Log moving along in body of water 2'
But the alert does display (screenshot) this message with a few boxxes before and after the message, I think this is causing the undefined error.
Is there any solution my var can be converted into only text?
Thanks in advance, Tjalle
You're trying to use title1 before it's defined. swap the lines
var title1 = $('#node-264152').find('.audio-description').html();
var linkText = document.createTextNode(title1);
Should be noted that since you're already using jQuery, you could do
var title1 = $('#node-264152').find('.audio-description').html();
$('<a />', {
href : 'http://www.someprivatelink.net',
title : title1,
text : title1
}).appendTo('body');

appendChild null | javascript/html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm following a tutorial online on how to make a to do list, found here:
https://www.youtube.com/watch?v=MURDw0-BiEE
I've following it pretty closely, but it won't work. Browser states the appendChild is null. The tutorial is 2 years old, could a part of the code be outdated? I had it sending alerts through the button, but when I changed to the appendChild things stopped working.
I'm pretty new to this and really appreciate the help.
function addNewItem() {
var listItem = document.createElement("li");
listItem.innerText = "Hello";
list.appendChild(listItem);
}
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
addNewItem(document.getElementById("todoList"));
};
And here's the related part of the HTML:
<p><button id="btnAdd">New Item</button></p>
<ul id="todolist">
</ul>
<script src="todo.js"></script>
</body>
You have defined your function without arguments and then you try to pass one :
function addNewItem(list) {}
P.S. : You also tried to getElementById todoList instead of todolist, so it also gave you error :
addNewItem(document.getElementById("todolist"));
JSFiddle
You've missed function parameter, list:
function addNewItem(list) {
var listItem = document.createElement("li");
listItem.innerText = "Hello";
list.appendChild(listItem);
}
var btnNew = document.getElementById("btnAdd");
btnNew.onclick = function() {
addNewItem(document.getElementById("todoList"));
};
You are passing a parameter to the function addNewItem() with addNewItem(document.getElementById("todoList")), but you aren't declaring this parameter in your function. So the variable list becomes null and appendChild() does not work. So change your first line:
function addNewItem() {
to
function addNewItem(list) {
and it will work.

improving my Javascript code: set a style of a link in page nav bar [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
a javascript+DOM question.
Can someone improve my code?
I have a page nav bar like this (on some pages):
<div id="pagebar">
1
2
3
4
5
6
</div>
I want my javascript to change the link style so that the style of the current page is highlighted.
My javascript code is this. It finds the current page's url, then try to match it with one of the link tag. If match, then set style.
function setPageBarStyle() {
var pageNavBar = document.getElementById("pagebar");
if (pageNavBar != null) {
var fPath = document.location.pathname;
var fPathParts = fPath.split('/');
var fName = (fPathParts[fPathParts.length-1]); // file name after last slash. e.g. xyz.html
var linkTags = pageNavBar.getElementsByTagName("a");
for (var ii = 0; ii < linkTags.length; ii++) {
var aUrl = linkTags[ii].href;
var aUrlParts = aUrl.split("/");
var aUrlLastPart = (aUrlParts[aUrlParts.length-1]); // part after last slash. e.g. xyz.html
if (aUrlLastPart == fName) {
linkTags[ii].style.border="thin solid blue";
}
}
}
}
setPageBarStyle();
How can i improve the code? I am new to DOM scripting.
The way i split the path seem too verbose, with many variables. I think it can be done with regex, but don't know how with javascript/DOM.
Thanks.
You can change this:
var aUrl = linkTags[ii].href;
var aUrlParts = aUrl.split("/");
var aUrlLastPart = (aUrlParts[aUrlParts.length-1]); // part before last slash. e.g. xyz.html
With this:
var aUrlLastPart = linkTags[ii].href.split("/").pop();
The Pop() method will return the last element of the array returned by split() and remove it from the array (which in your case, is irrelevant).
I would also recommend checking out jQuery or similars, in order to manage cross browser JS easier...
Let me know if it helps! :)

Categories

Resources