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

Share:
20,386
Vaibhav Ahalpara
Author by

Vaibhav Ahalpara

Updated on September 30, 2020

Comments

  • Vaibhav Ahalpara
    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

  • Sikshya Maharjan
    Sikshya Maharjan over 9 years
    No, $(".classname")[0] will retrieve the DOM node from the jQuery collection, which has no text() method. You could use $(".classname").eq(0).text('...') though.
  • Christos
    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
    Sikshya Maharjan over 9 years
    No, $(".classname")[0] will retrieve the DOM node from the jQuery collection, which has no val() method. You could use $(".classname").eq(0).val('...') though. Or you could, if the <a> element had a val() method.
  • Hoja
    Hoja over 9 years
    @DavidThomas. Thankx for your valuable comment. I've edited my answer