-3

I want to insert html using JavaScript with something like this : document.getElementById("demo").innerHTML = "example"; but i do not want to use id how can i do it by class name? I have tried document.getElementsByClassName("demo").innerHTML = "example"; but it did not work either...or is there any why to insert html other than innerHTML using classes ..

shadi
  • 113
  • 1
  • 9
  • 2
    `document.getElementsByClassName('class')`. It'll return an array of elements so you'll have to work with that. – Phiter Oct 31 '18 at 14:44
  • @Phiter is correct. getElementsByClassName returns an array of elements, you may use the index and target any element. If you think you have only one item or want to target first item use this snippet. document.getElementsByClassName('demo')[0].innerHTML = "example"; – Amit Bhoyar Oct 31 '18 at 14:59

3 Answers3

-1

You can use any css selector using the query selector function. See here for more details: querySelector

If you want to do an action for every element that matches your css selector, use querySelectorAll instead, which returns a nore list. querySelectorAll

Alkis Mavridis
  • 1,090
  • 12
  • 28
-2

document.getElementsByClassName("example");

Andy
  • 49,085
  • 60
  • 166
  • 233
Mike
  • 184
  • 9
-3

Try by class document.getElementsByClassName("demo").innerHTML = "TEXT/HTML"

or

By tag document.getElementsByTagName("p").innerHTML = "TEXT/HTML"

You can see this methods here on documentation:

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName

Robson Braga
  • 432
  • 3
  • 8