最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS setattribute is not a function- Firefox, chrome - Stack Overflow

programmeradmin25浏览0评论

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.

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.

Share Improve this question edited May 16, 2016 at 15:15 Cal Jacobson 2,4071 gold badge26 silver badges35 bronze badges asked Oct 29, 2013 at 5:55 mnmnmnmnmmnmnmnmnm 2691 gold badge3 silver badges8 bronze badges 2
  • SetAttribute should work, pls check whether you get correct object in "txtEndDate" – AmGates Commented Oct 29, 2013 at 6:12
  • Can you post your whole code in Js fiddle pls – AmGates Commented Oct 29, 2013 at 6:12
Add a comment  | 

3 Answers 3

Reset to default 32

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);
}

You can do it by this way:

txtEndDate['dateInRegionalFormat'] = txtEndDate.value;

instead of old code:

txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate.value);

I have faced the same kind of issue very recently. Try to get rid of ".value" part. It may work for you.

txtEndDate.setAttribute('dateInRegionalFormat', txtEndDate);
发布评论

评论列表(0)

  1. 暂无评论