1

I am having a slight problem with the .setAttribute command. I am creating an element called view:

var view = document.createElement('p')
view.innerHTML = "VIEW"
view.style.color = "#e60f0f"
view.style.fontFamily = "Montserrat"
view.style.fontWeight = "600"
view.style.fontSize = "13px"
view.style.right = "5px"
view.style.position = "absolute"
view.style.top = "0px"
view.style.marginTop = "5px"
view.style.backgroundColor = "transparent"
view.style.padding = "10px"
view.style.borderRadius = "7px"
view.setAttribute('onclick', 'view(name, date, type)')
document.getElementById(newId).appendChild(view)

When I run this, everything renders except the .setAttribute() function. I don't have the sligthest idea why. Does anyone know? Thank you SO much!

Here's the view() function in case you need it:

function view(name, date, type) {
  window.location = '/flightStatus?name=' + name + '&date=' + date + '&type=' + type
}

Just as another note: I am sending this to Node.js... I don't think that matters, the code above is client-side :)

D. Dog
  • 15
  • 3

2 Answers2

1

You would only be able to use strings in your inline method. That would looks something like this (or using template literals):

view.setAttribute('onclick', 'view(\'' + name + '\', \'' + date + '\', \'' + type + '\')')

You should use proper DOM Methods though. Simply replace

view.setAttribute('onclick', 'view(name, date, type)')

with

view.addEventListener('click', () => view(name, date, type));
marks
  • 1,501
  • 9
  • 24
0

You need to escape the variables in this line: view.setAttribute('onclick', 'view(name, date, type)')

I would've used template literals:

view.setAttribute('onclick', `view(${name}, ${date}, ${type})`)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

If you are unsure of whether to use addEventListener or onClick:

addEventListener vs onclick

Salmin Skenderovic
  • 1,750
  • 9
  • 22