Return to Video

Setting InnerHTML and textContent (Video Version)

  • 0:01 - 0:07
    We've already used `innerHTML` quite a bit
    here, but I want to quickly show you
  • 0:07 - 0:09
    a little more about it.
  • 0:09 - 0:14
    First, let's look at our example,
    right here where we set `innerHTML`.
  • 0:14 - 0:18
    I've just passed in a string,
    "all about cats".
  • 0:18 - 0:22
    But, in fact, I could put HTML tags
    inside that string.
  • 0:22 - 0:27
    So I could surround "cats"
    with `` tags,
  • 0:27 - 0:29
    and you can see it shows up emphasized.
  • 0:29 - 0:33
    Or down here, where I
    change "dog" to "cat",
  • 0:33 - 0:36
    I could surround this
    with `` tags,
  • 0:36 - 0:39
    and it shows up strong, bold.
  • 0:39 - 0:44
    I could even write an `` tag
    inside here, or put an entire webpage's
  • 0:44 - 0:48
    HTML in here, if I really wanted.
  • 0:48 - 0:54
    So that's pretty neat, because it means
    we can do a lot with `innerHTML`.
  • 0:54 - 0:59
    If we're only changing the text, actually,
    we don't even need to use `innerHTML`.
  • 0:59 - 1:04
    We can just use the `textContent`property,
    and that means that browser
  • 1:04 - 1:09
    won't interpret what you pass as HTML,
    and will just render it as plain text.
  • 1:09 - 1:12
    Notice if I change this to `textContent`,
  • 1:12 - 1:15
    my brackets show up-- gross!
  • 1:15 - 1:19
    So, in that case, we're just going to
    get rid of them, because the browser
  • 1:19 - 1:23
    refuses to turn them into actual HTML.
  • 1:23 - 1:27
    So if you do want to just set the text,
    just use `textContent`.
  • 1:27 - 1:32
    If you want to pass in some HTML tags,
    and have them interpreted as HTML,
  • 1:32 - 1:35
    then use `innerHTML`.
  • 1:35 - 1:38
    Once you start doing more
    advanced DOM manipulation,
  • 1:38 - 1:42
    you should be more careful about
    using `innerHTML` and `textContent`,
  • 1:42 - 1:45
    because they'll also
    remove event listeners
  • 1:45 - 1:47
    that you've attached to the
    elements inside,
  • 1:47 - 1:49
    which you'll learn how to do soon.
  • 1:49 - 1:52
    In the next talk-through, I'll show you
    a more sophisticated way
  • 1:52 - 1:55
    to insert new elements
    and text in your page.
Title:
Setting InnerHTML and textContent (Video Version)
Description:

more » « less
Video Language:
English
Duration:
01:57

English subtitles

Revisions