Saturday, November 9, 2024

JavaScript, innerHTML and innerText

In JavaScript, innerHTML and innerText are both properties used to get or set the content inside an HTML element, but they behave differently in certain situations. Here's a breakdown of their differences with examples:

1. innerHTML

The innerHTML property gets or sets the HTML content inside an element. It includes HTML tags and renders any HTML elements within the content.

Example:

<div id="example1">
  <p>Hello <strong>World</strong></p>
</div>

<script>
  // Get the HTML content
  let content = document.getElementById("example1").innerHTML;
  console.log(content); // Output: <p>Hello <strong>World</strong></p>
  
  // Set new HTML content
  document.getElementById("example1").innerHTML = '<p>New <em>Content</em></p>';
</script>
Explanation: innerHTML will return the HTML markup, including the tags. In this example, it returns the HTML structure, not just the text.

2. innerText

Description: The innerText property gets or sets the plain text content inside an element. It does not include any HTML tags and can be affected by CSS styles like display: none.

Example:

<div id="example2">
  <p>Hello <strong>World</strong></p>
</div>

<script>
  // Get the text content
  let textContent = document.getElementById("example2").innerText;
  console.log(textContent); // Output: Hello World (no tags)
  
  // Set new text content
  document.getElementById("example2").innerText = 'New Content';
</script>

Explanation: innerText returns only the plain text content of the element, stripping away the HTML tags. In this case, the &lt;strong&gt; tag is ignored, and only the text "Hello World" is returned.

Key Differences:

  • HTML vs. Plain Text: innerHTML includes HTML tags in the returned content, whereas innerText only includes visible text.
  • Performance: Setting innerHTML may trigger reflow and repaint, which can be more performance-costly than innerText.
  • CSS Impact: innerText is affected by CSS styles like display: none (i.e., it won't include text of hidden elements), while innerHTML is not.

Summary:

  • Use innerHTML when you need to work with HTML tags and structure.
  • Use innerText when you need to work with just the plain text.

No comments:

Post a Comment

Hot Topics