HTML
<a href="#1" class="current">1</a>
<div id="xyz"></div>
JavaScript
function updateHash() {
var number = document.querySelectorAll('.current')[0].innerHTML;
document.querySelector('#xyz').innerHTML = '<a>'+ number + '</a>';
}
updateHash();
Obviously, this works.
However, I need the <a>
to be <a href="#>
So when I do that:
document.querySelector('#xyz').innerHTML = '<a href="#'+ number + '"</a>';
It fails.
I don't know if this can be resolved with escaping the character; when I tried to escape " & #, it didn't work.
Maybe there isn't a way to escape the character for this scenario.
Any help would be greatly appreciated.
[Update]
I solved it this way.
function updateHash() {
var number = document.querySelectorAll('.current')[0].innerHTML;
var tag = '<a href=#'
document.querySelector('#xyz').innerHTML = tag + number + '>next</a>';
}
updateHash();
Actually, I was doing the same thing as before. But as pointed out, I wasn't seeing any output because my href was empty. LOL
a
tag <a></a>
innerHTML
of the a
tag is empty .so is not visible but its there in your body
your mistake .kindly check the outerHTML
function updateHash(){
var number = document.querySelectorAll('.current')[0].innerHTML;
document.querySelector('#xyz').innerHTML = '<a href="#'+ number + '"</a>';
console.log(document.querySelector('#xyz').outerHTML)
}
updateHash();
<a href="#1" class="current">1</a>
<div id="xyz"></div>
solved
function updateHash(){
var number = document.querySelectorAll('.current')[0].innerHTML;
document.querySelector('#xyz').innerHTML = '<a href="#'+ number + '">innerhtml is empty</a>';
console.log(document.querySelector('#xyz').outerHTML)
}
updateHash();
<a href="#1" class="current">1</a>
<div id="xyz"></div>