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

jquery - how to change value of html element by classname using javascript - Stack Overflow

programmeradmin6浏览0评论

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

<a class="classname" href="Vtech"> 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

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

<a class="classname" href="Vtech."> 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

Share Improve this question edited Jan 13, 2015 at 9:15 Oleksandr T. 77.5k17 gold badges176 silver badges145 bronze badges asked Jan 13, 2015 at 9:12 Vaibhav AhalparaVaibhav Ahalpara 2441 gold badge7 silver badges22 bronze badges 1
  • its working see here – Kartikeya Khosla Commented Jan 13, 2015 at 9:15
Add a ment  | 

5 Answers 5

Reset to default 11

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

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

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

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

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");
});
发布评论

评论列表(0)

  1. 暂无评论