Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS setattribute is not a function- Firefox, chrome

I have this JavaScript function:

function Test(isValid) {    
    var divStart = $get('divDateFrom');
    var divEnd = $get('divDateTo');
    var txtStartDate = divStart.firstChild;
    var txtEndDate = divEnd.firstChild;
    var isValidFromForecastStartDate;
    txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate.value);
}

This function is working fine in IE but I'm getting "txtEndDate.setattribute is not a function" error in Firefox and Chrome.

like image 243
mnmnmnmnm Avatar asked Oct 29 '13 05:10

mnmnmnmnm


People also ask

Why is setAttribute not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).

How to use setAttribute?

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 to replace attribute in JavaScript?

Another way to change or create an attribute is to use a method like element. setAttribute("attribute", "value") or element. createAttribute("attribute", "value"). Use setAttribute to change an attribute that has been defined before.

How to set an attribute in JS?

JavaScript setAttribute() The setAttribute() method is used to set or add an attribute to a particular element and provides a value to it. If the attribute already exists, it only set or changes the value of the attribute. So, we can also use the setAttribute() method to update the existing attribute's value.


1 Answers

Use jquery.attr() like,

$(txtEndDate).attr('dateInRegionalFormat', txtEndDate.value);

Updated there may be multiple elements so use [0] for the first element like,

txtEndDate[0].setAttribute('dateInRegionalFormat', txtEndDate.value);

You should first check whether the elements exists or not before setting attribute in it like,

if(txtEndDate.length)
{
   txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate.value);
}
like image 78
Rohan Kumar Avatar answered Oct 17 '22 01:10

Rohan Kumar