Javascript for adding a custom attribute to some elements

前端 未结 4 1623
渐次进展
渐次进展 2021-02-01 13:22

Given a section of HTML, can I selectively pick some types of elements (e.g., input) and add a custom attribute using JavaScript? I would also need to remove this attribute if i

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 13:55

    Hello!

    Adding attribute via javascript:

    var myDiv= document.getElementsByClassName("first-div")[0];
    var myp= myDiv.children[0];
    nyp.setAttribute('myAttribute','valueForAttribute');
    

    getting the attribute via javascript:

       console.log(myp.getAttribute('myAttribute'));
    

提交回复
热议问题