How to mix string with variables in an input needing mutiple values in js? (In this case, the coord attribute of the area tag)

42 Views Asked by At

So what the problem I have been facing so far is that I am currently trying to use javascript so that the coords attribute of my area tag is set according to some variables(what it is doesn't really matter). However, the coords require 4 inputs (x1,y1,x2,y2) and I have some values that I am not going to use the variable for. Which means that I have to mix string and variables in the input which I have no idea on how to do.

To give you a better sense on what I am doing, here is a summary:

var p = some random value
var q = some random value

var a1 = document.getElementById(areaID);
a1.setAttribute("coords", "0,0, p,q")

Of course this didn't work as the "" made it think that p,q are strings instead of variables. So I tried some other where it all failed(some desperate attempts).

a1.setAttribute("coords", 0,0,p,q);
a1.setAttribute("coords", "0,0," + p + "," + q);
document.getElementById(areaID).coords = 0,0, p,q;

const list = ["0","0", p,q];
a1.setAttribute("coords", list);

So does anyone know how could I possibly do this?

1

There are 1 best solutions below

1
Timur On

The second option you tried should work. In your example, is areaID a variable or the actual id of the element? If it is the latter, then you need to put it in quotes: document.getElementById("areaID")

var p = "val1"
var q = 23

var a1 = document.getElementById("areaID");
a1.setAttribute("coords", "0,0," + p + "," + q)

console.log(a1);
<div id="areaID"></div>