I have an HTML page that has javascript, I'd like the javascript to generate HTML buttons like this:
<button class="btnFormat" onclick="var link = document.createElement('a');
link.href = '#xxxxx';
link.click(); window.location.reload() "> AYOU1 </button>
<button class="btnFormat" onclick="var link = document.createElement('a');
link.href = '#xxxxx';
link.click(); window.location.reload() "> AYOU1 </button>
<button class="btnFormat" onclick="var link = document.createElement('a');
link.href = '#xxxxx';
link.click(); window.location.reload() "> AYOU1 </button>
I can't seem to figure out how to get the javascript to add the class or onClick 'strings'. My code runs without errors but looking at the output it is just:
<button>AYOU1</button>
<button>AYOU2</button>
<button>AYOU3</button>
This is the code that I have been working on (it doesn't have the class=, as I can't figure out the onClick= part...):
<html>
<body>
<script>
var items = [
{hex: "OBFPUOX6T", alpha: "AYOU1" },
{hex: "LC7THLODH", alpha: "AYOU2" },
{hex: "RNPODALAJ", alpha: "AYOU3" },
{hex: "2FSCQ4LGK", alpha: "AYOU4" },
]
var i = 0;
const parentElement = document.querySelector('body'); // DOM location when buttons will be added
items.forEach(function(item) {
const pButton = document.createElement("button");
pButton.innerText = item.alpha;
pButton.onClick = function() {
var link = document.createElement('a');
link.href = '#' + item.hex;
window.location.reload();
};
i++;
console.log(pButton, i)
parentElement.appendChild(pButton); // to add new element to DOM
})
</script>
</body>
</html>
I would appreciate any help! Thank you in advance!
I added the full source code here: https://jsfiddle.net/kilimar/7eL15azm/
If your output doesn't show any classes, it's because all of the events are handled in the background, it is also probably a good practice to do it that way.
Though, your script have some errors and can be simplified:
pButton.onclick is lowercase (not pButton.onClick)
pButton.onclick = function() { // [...]
Then there's a very useful property: location.hash (also window is not necessary)
location.hash = '#' + item.hex;
location.reload();
(Bonus!) there's a shortcut for document.querySelector('body')
const parentElement = document.body
Anyways, here's the whole code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var items = [
{hex: "OBFPUOX6T", alpha: "AYOU1"},
{hex: "LC7THLODH", alpha: "AYOU2"},
{hex: "RNPODALAJ", alpha: "AYOU3"},
{hex: "2FSCQ4LGK", alpha: "AYOU4"},
]
var i = 0;
const parentElement = document.body; // DOM location when buttons will be added
items.forEach(function(item) {
const pButton = document.createElement("button");
pButton.innerText = item.alpha;
pButton.onclick = function() {
location.hash = '#' + item.hex;
location.reload();
};
i++;
console.log(pButton, i)
parentElement.appendChild(pButton); // to add new element to DOM
})
</script>
</body>
</html>
I hope this helped !