javascript 如何使用javascript通过类名更改html元素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27918478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:10:09  来源:igfitidea点击:

how to change value of html element by classname using javascript

javascriptjqueryclassanchorinnerhtml

提问by Vaibhav Ahalpara

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

这是我用来更改 html 元素值的代码 ***

<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

如何在页面加载实例上更改此文本

回答by Alexander T.

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

似乎您需要DOMContentLoaded在之前添加或放置脚本</body>

Native JavaScript solution

原生 JavaScript 解决方案

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


Add your script before </body>

之前添加你的脚本 </body>



Version with jQuery

带有 jQ​​uery 的版本

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

回答by degr

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

您可以使用 css 选择器,但它可能不安全,因为此方法返回第一次出现:

document.querySelector(".classname");

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

顺便说一句,几乎所有的开发者都使用一些js框架:jQuery、prototype、extJs等

回答by Afzal Ahmad

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

回答by Hoja.M.A

You could use this

你可以用这个

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

Using jQuery

使用 jQuery

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

回答by Christos

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

使用 jquery(我指的是 jquery,因为你已经在你的问题中标记了它),你可以像下面这样实现:

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