I'm changing the HTML using javascript. Therefore, I have a String that saves the HTML code, since it is produced in a for-loop. In it there is an <a> tag. To the <a> tag I want to add an onClick which calls a function with a parameter which is saved in a javascript variable.
let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window("+parameter+")'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;
This does not work because it would prodece the following html:
<a href='#' onClick='create_sprite_window(p1)'></a>
It does not work because there are no quotation marks before and after p1.
My problem is that I would need a third kind of quotation marks in order to solve this.
In the following example I will use # where I would need those quotation marks:
let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window(#"+parameter+"#)'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;
I can't use a single quotation mark because it would end the onClick and I can't use double beacuse it would end to_html_String.
Are there third quotation marks or is there an other way to solve this?
If you're using ES6, you can use template strings like
let foo = `Hello "World's"`;
Anyway - why wouldn't you just escape your quotation marks ?
let bar = 'hello \' world';
let buz = "hello \" world";
Don’t build HTML using JavaScript. The DOM API will let you build document nodes cleanly and safely, and even attach event listeners so you don’t have to build JavaScript strings in the HTML you’re building in JavaScript.
let parameter = "p1";
const link = document.createElement('a');
link.href = '#';
link.textContent = 'maybe you want something in this link?';
link.addEventListener('click', function (e) {
e.preventDefault();
create_sprite_window(parameter);
});
document.getElementById('sidebar_left_sprites')
.appendChild(link);
createElement
addEventListener
appendChild
This will work
"<a href='#' onClick='create_sprite_window('"+parameter+"')></a>";
/* Use \' to differentiate with function single quote */
let parameter = "p1";
let to_html_String = "";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;
Related
I'm trying to create a button that links to a random page in my simple website. I'm having issues modifying the "href" and making it go to the page on the click.
Here is the JavaScript I have written:
document.addEventListener("DOMContentLoaded", function(){
let arrayofpages = ["my_cat.html","about_me","art.html","index.html"]
let randompage = arrayofpages[Math.floor(Math.random()*arrayofpages.length)];
document.addEventListener("click",function(){
document.getElementById("lucky_btn").href = "${randompage}";
document.getElementById("lucky_btn").innerHTML = "random page";
});
The string "${randompage}" is literally just a string that says "${randompage}". Instead, use backticks:
`${randompage}` // This creates a string out of the variable randompage
But in your case, since you're not doing anything with the string, the simplest way is to use the variable directly:
document.getElementById("lucky_btn").href = randompage;
In general, template literals are more useful for inserting variables into a longer string, like
let name = 'Sarah';
let quality = 'great';
let message = `Hello ${name}, have a ${quality} day`;
A little bug in your code. you used double quotes "" instead of backticks ``.
This line
document.getElementById("lucky_btn").href = "${randompage}";
should be
document.getElementById("lucky_btn").href = `${randompage}`;
I have found the bug that was causing the issue, of not redirecting to a random page:
instead of
document.getElementById("lucky_btn").href = "${randompage}";
where I should have used backticks, I changed the code to:
document.location.href = `${randompage}`;
and this has solved the problem!
I have a system that dynamically generates links. but the html links are displayed like this :
Page Example
there's a way to remove the repetition of <a> tags using JS ? so, the link becomes :
Page Example
Let's take a look at your url:
var url='Page Example';
First let's get rid of both occurences of "
url=url.replace(/"/g,'');
Now remove the first occurence of </a> by feeding the exact string instead of a regular expression to the .replace method.
url=url.replace('</a>','');
At this point your url looks like this:
Page Example
We're getting closer. Let's remove anything in between the > and the " by
url=url.replace(/\>(.*)\"/,'"');
which gives us
Page Example
Almost done - finally let's get rid of "<a href=
url=url.replace('"<a href=','"');
To make the whole thing a bit more beautiful we can chain all four operations:
var url = 'Page Example';
url = url.replace(/"/g, '').replace('</a>', '').replace(/\>(.*)\"/, '"').replace('"<a href=', '"');
console.log(url);
Within your process you can use regex to extract the url from the href string:
const string = "<a href="/page-example">Page Example</a>";
const url = string.match(/(\/)[\w-]*(?=&)/)[0];
console.log(url);
Yes, using the string split() function like this...
S='<a href="/page-example">Page Example</a>';
var A=split('"');
document.write(A[1]);
This should display "/page-example", and you can then add it as the href to an anchor.
You can retrieve the hrefvalue that seems to be the correct A element and replace the incorrect one with the correct one:
const a = document.querySelector('a[href]'); //if you have more <a> elements replace it to your need
const attr = a.getAttribute('href'); //get the value of 'href' attribute
const temp = document.createElement('template');
temp.innerHTML = attr; //create the new A element from the 'href' attribute's value
const newA = temp.content.children[0]; //retrieve the new <a> element from the template
a.parentElement.replaceChild(newA, a); //replace the incorrect <a> element with the new one
Page Example
In my web app I have various .jspx pages, in one of this I want compose it dinamically by javascript.
I want to create a table with the data element, every data element have an index.
I compose a var, named url, with the path and the id of element:
var url = "${downloaHistodyUrl}"+data[index].id;
My problem is that the url is set correctly (I had used the alert for debug it). But, when I click on: <a href> element I have the "url" world, instead of the value of the variable and my path is: "/mypath/"+url+ .
CODE:
$('#modal_history_${doc.id}').on('show.bs.modal', function(e) {
$.getJSON('${historyUrl}', function(data) {
var html='<table class="table table-hover"><tr><th>Versione</th><th>Nome</th><th>PDF</th><th>Motivazione</th></tr>';
$.each(data, function(index) {
html = html+"<tr><td>"+data[index].versione+"</td>";
if(data[index].fileName != null){
var url = "${downloaHistodyUrl}"+data[index].id;
alert(url);
html = html+'<td>'+data[index].fileName+'</td><td> Download</span></td>';
}else{
html = html+"<td></td>";
}
if(data[index].motivazione == "" || data[index].motivazione == null){
html = html+"<td></td>";
}else{
html = html+"<td>"+data[index].motivazione+"</td>";
}
html = html+'</tr>';
});
html = html+'</table>';
$('#content_modal_history_${doc.id}').append(html);
})
});
I don't understand why..
Anyone can help me?
You're missing the double quotes on the href attribute.
You have <a href=myurl while it needs to be <a href="myurl"
Also, double-check that you really used single quotes when adding url to the string and not double quotes. If you did something like this, it would exactly cause the problem you're describing:
html = 'click me'
Your code should read like this:
html = html+'<td>'+data[index].fileName+'</td><td><span class="fa fa-download"> Download</span></td>';
The problem is that you need to escape the slash '/' characters in your url variable. Otherwise they will have the effect you are experiencing, that is, they will make the single quotes appear in the final output.
Edit: In case you didn't understand, what I mean is changing/replacing the slashes (/) with double slashes like (//). I also recommend you to use the concat method instead of using the add (+) operator for strings, for a cleaner code.
I'm inserting content with js, that includes an onclick call to a function. This function passes a parameter which contains a database entry, which could contain a ' .
var action = 'Share';
Trouble is that when name contains a single apostrophe it breaks the function call. I've tried doing a string replace on name to replace ' with ' but this seems to still be converted back to a ' by the browser.
Any idea how I can get around this?
Use escape() or after JavaScript version 1.5. use encodeURI() or encodeURIComponent() instead.
Don't write code by mashing strings together with other code. You've got JavaScript inside HTML inside JavaScript and it is a recipe for headaches.
Use DOM manipulation instead.
var a = document.createElement('a');
a.href = "#"; // You should use a button instead of a link to the top of the page
a.className = "facebook-share";
a.addEventListener('click', function () {
facebookWallPost(name);
});
a.appendChild(
document.createTextNode('Share');
);
I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.