-1

I'm trying to target all divs of a certain class and apply innerHTML. This is what I have, but I'm getting no errors and no result.

$( ".programdesc" ).innerHTML( '<p>I am alive</p>' );

Any pointers?

Miles Pfefferle
  • 1,187
  • 6
  • 20
  • 36

4 Answers4

3

Use the html function :

$( ".programdesc" ).html( '<p>I am alive</p>' );
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • This is kind of a really nit-picky comment, but this will get all elements with that class, not just `div`s. I would guess that it ends up making no difference in OP's code. – ajp15243 Dec 10 '13 at 20:26
  • 2
    @ajp15243 Right. OP, if that's a issue for you, use `$('div.programdesc')`. Note that if it's not a problem, it's better (faster) to just have the class in the selector. – Denys Séguret Dec 10 '13 at 20:28
  • Will this get all elements with that class, even if they have additional classes? – Miles Pfefferle Dec 10 '13 at 20:30
  • @miles yes, it would. – Kevin B Dec 10 '13 at 20:30
  • Ah, got it to work (script was in the wrong place, needed to be after the content). However, this method replaces the HTML. I saw the Append method in an answer below and tried that, and voila! Sorry, should have specified I wanted to append html. – Miles Pfefferle Dec 10 '13 at 20:38
  • @miles Then use `append` instead of `html`. – Denys Séguret Dec 10 '13 at 20:40
2

Try:

$("div.programdesc").append('<p>I am alive</p>');

DEMO

codingrose
  • 15,563
  • 11
  • 39
  • 58
0

You should use each

$( "div.programdesc" ).each(function() {
 (this).innerHTML( '<p>I am alive</p>' );
});

http://api.jquery.com/each/

Eisa Adil
  • 1,743
  • 11
  • 16
0

innerHTML is a property of a DOM Element, not a function. The property exists in pure Javascript, not in jQuery statements.

$(".programdesc").html( 'this is the jQuery way' );

document.getElementsByClassName('programdesc').index(0).innerHTML = "This is the Javascript way";
dockeryZ
  • 3,981
  • 1
  • 20
  • 28
  • The second one doesn't work. Live node lists don't have this properties. – Denys Séguret Dec 10 '13 at 20:29
  • Well, you're definitely right about that, but the OP said nothing about capturing live elements. If that's the problem, go here http://stackoverflow.com/a/9106397/401299 – dockeryZ Dec 10 '13 at 20:32
  • *"all divs of a certain class"* – Denys Séguret Dec 10 '13 at 20:40
  • The word 'certain' connotes something specific....something particular. `$('.certain')` will catch all particular elements whose class contains certain....Now, if he had said dynamic instead, I would agree with you. – dockeryZ Dec 10 '13 at 20:43
  • 1
    And JavaScript is definitely not one you know... Just test your code. You'll see that the live list returned by `document.getElementsByClassName` simply doesn't have any `innerHTML`property... – Denys Séguret Dec 10 '13 at 20:48