how to change value of html element by classname using javascript

倾然丶 夕夏残阳落幕 提交于 2020-01-13 11:54:47

问题


Here is the code i am using to change value of html element ***

<a class="classname" href="Vtech.com"> This text to be chnage</a>

<script type="text/javascript">
document.getElementsByClassName("classname")[0].innerHTML = "aaaaaaqwerty";
</script>

how can I change this text on page load instans


回答1:


Seems you need to add DOMContentLoaded or put your script before </body>

Native JavaScript solution

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementsByClassName("classname")[0].innerHTML = "qwerty";
});

Add your script before </body>


Version with jQuery

$(funtion(){
   $(".classname:first").text("qwerty");
});



回答2:


You can use css selector, but it can be not safe, because this method return first occurance:

document.querySelector(".classname");

By the way, almost all developers use some js framework: jQuery, prototype, extJs, etc




回答3:


$(document).ready(funtion(){
    $(".classname").text("aaaaaaqwerty");
});



回答4:


Using jquery (I refered to jquery, since you have tagged it in your question), you could achieve this like below:

$(funtion(){
    $("a .classname")[0].text("aaaaaaqwerty");
});



回答5:


You could use this

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementsByClassName("classname")[0].innerHTML = "some texts";
});

Using jQuery

$(document).ready(function(){
   $(".classname").eq(0).val("aaaaaaqwerty");
});


来源:https://stackoverflow.com/questions/27918478/how-to-change-value-of-html-element-by-classname-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!