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..
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.
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() .
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.
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.
Try this:
document.getElementById("countryscript").setAttribute("data-main", countrycode);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With