how to change value of html element by classname using javascript
20,386
Solution 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");
});
Solution 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
Author by
Vaibhav Ahalpara
Updated on September 30, 2020Comments
-
Vaibhav Ahalpara over 3 years
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
-
Kartikeya Khosla over 9 years
-
-
Sikshya Maharjan over 9 yearsNo,
$(".classname")[0]
will retrieve the DOM node from the jQuery collection, which has notext()
method. You could use$(".classname").eq(0).text('...')
though. -
Christos over 9 years@DavidThomas you are correct ! Thank you very much. I think that my edit also do the same thing that you referred to. Correct? I mean the selector is correct now. Thank you in advance for your response.
-
Sikshya Maharjan over 9 yearsNo,
$(".classname")[0]
will retrieve the DOM node from the jQuery collection, which has noval()
method. You could use$(".classname").eq(0).val('...')
though. Or you could, if the<a>
element had aval()
method. -
Hoja over 9 years@DavidThomas. Thankx for your valuable comment. I've edited my answer