-1

I am trying to change inner html of an element. If we use this:

$('.best-photos-button')[0].innerHTML="Add More Photos";

it works fine. But if instead of ".innerHTML" i.e. JavaScript if we use .html() like this :

$('.best-photos-button').html("Add More Photos");

then it's not working. Why so? When I am running $('.best-photos-button').innerHTML on console it's giving undefined.

Ali Rezaie
  • 388
  • 8
  • 23
Laveena
  • 97
  • 1
  • 10
  • Does this answer your question? [How do I get first element rather than using \[0\] in jQuery?](https://stackoverflow.com/questions/3103810/how-do-i-get-first-element-rather-than-using-0-in-jquery) – Gerard Mar 05 '20 at 06:20
  • remove `[0]` from the script `$('.best-photos-button').html("Add More Photos");` – Ismail Vittal Mar 05 '20 at 06:21
  • What makes you think that it **should** be defined? Are you refering to some documentation? – Nico Haase Mar 05 '20 at 12:59
  • I put a debugger on js in browser and try to get the value of $('.best-photos-button').innerHTML and output for that should be whatever is in the text in the selected element but it's giving undefined. Hope that helps! – Laveena Mar 06 '20 at 06:27

1 Answers1

4

$('.best-photos-button') is a jQuery object. When you use $('.best-photos-button')[0] it will return the raw DOM element, which does not have a .html() method, only .innerHtml.

So you either need to use

$('.best-photos-button').html("Add More Photos"); 

or use .innerHtml

Edit: Note that if you use .html() it will affect all the elements with best-photos-button class. So depending on your use case you might need to use a different selector or filter the selection to get the specific object you need.

Cray
  • 2,774
  • 7
  • 22
  • 32
  • 1
    Further clarification [here](https://stackoverflow.com/questions/6974582/jquery-object-and-dom-element) – Swimmer F Mar 05 '20 at 06:22
  • if I am using $('.best-photos-button').html("Add More Photos"); it's not working. The code is breaking. Also $('.best-photos-button') is added to a single element only. – Laveena Mar 05 '20 at 06:43
  • Are you calling the method before DOM is loaded? You can use [document "ready"](https://learn.jquery.com/using-jquery-core/document-ready/) to make sure the element is loaded before trying to modify it. – Cray Mar 05 '20 at 06:49
  • if that's the case then how this is working : $('.best-photos-button')[0].innerHTML="Add More Photos"; – Laveena Mar 05 '20 at 08:27
  • 1
    I'm only guessing, can't say much when there is only 1 line of code. – Cray Mar 05 '20 at 08:35