Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← Setting InnerHTML and textContent (Video Version)

Get Embed Code
7 Languages

Showing Revision 1 created 03/05/2015 by Josh Kline.

  1. We've already used `innerHTML` quite a bit
    here, but I want to quickly show you
  2. a little more about it.
  3. First, let's look at our example,
    right here where we set `innerHTML`.
  4. I've just passed in a string,
    "all about cats".
  5. But, in fact, I could put HTML tags
    inside that string.
  6. So I could surround "cats"
    with `` tags,
  7. and you can see it shows up emphasized.
  8. Or down here, where I
    change "dog" to "cat",
  9. I could surround this
    with `` tags,
  10. and it shows up strong, bold.
  11. I could even write an `` tag
    inside here, or put an entire webpage's
  12. HTML in here, if I really wanted.
  13. So that's pretty neat, because it means
    we can do a lot with `innerHTML`.
  14. If we're only changing the text, actually,
    we don't even need to use `innerHTML`.
  15. We can just use the `textContent`property,
    and that means that browser
  16. won't interpret what you pass as HTML,
    and will just render it as plain text.
  17. Notice if I change this to `textContent`,
  18. my brackets show up-- gross!
  19. So, in that case, we're just going to
    get rid of them, because the browser
  20. refuses to turn them into actual HTML.
  21. So if you do want to just set the text,
    just use `textContent`.
  22. If you want to pass in some HTML tags,
    and have them interpreted as HTML,
  23. then use `innerHTML`.
  24. Once you start doing more
    advanced DOM manipulation,
  25. you should be more careful about
    using `innerHTML` and `textContent`,
  26. because they'll also
    remove event listeners
  27. that you've attached to the
    elements inside,
  28. which you'll learn how to do soon.
  29. In the next talk-through, I'll show you
    a more sophisticated way
  30. to insert new elements
    and text in your page.