Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set attribute using javascript variable

the following is my cshtml code inside durandal application

<script type="text/javascript" src="~/Scripts/require.js" 
  id="countryscript" data-main="**here i have to set value**"></script>

I want to set script attribute data-main with my javascript variable value. How to achieve this ?

I tried as

document.getElementById("countryscript").data-main = countrycode;

its showing syntax error near = sign. Need help..

like image 590
Pandiyan Cool Avatar asked Sep 23 '13 13:09

Pandiyan Cool


People also ask

How do you assign a variable to an attribute?

To assign a new value to the variable or attribute, double-click on the Assign statement and enter the new value. To increment/decrement the value of a variable or attribute, double-click on the Inc or Dec statement and enter the value by which the variable or attribute should be incremented/decremented.

What is set attribute in JavaScript?

Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .

How set JavaScript variable in HTML?

You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html. Save this answer.

Can JavaScript change attributes?

Javascript can be used to change the attribute(s) of a HTML element, such as a paragraph, a header, an image, or a list, or any various HTML elements. For example, by changing the src attribute of an img tag, we can change the image entirely to something else with Javascript.


2 Answers

Try this:

document.getElementById("countryscript").setAttribute("data-main", countrycode);
like image 58
Joorge Leal Avatar answered Sep 19 '22 15:09

Joorge Leal


Taken from MDN

var d = document.getElementById("countryscript"); 
d.setAttribute("data-main", countrycod);

Or if you have JQuery, this is much easier

$('#countryscript').attr("data-main", countrycod);
like image 40
Jhankar Mahbub Avatar answered Sep 20 '22 15:09

Jhankar Mahbub