HTML DOM Pre Object: Accessing Preformatted Text Elements

The HTML DOM Pre object represents an HTML <pre> element. The <pre> element is used to define preformatted text, which is displayed in a fixed-width font, preserving both spaces and line breaks. Through the DOM Pre object, you can access and manipulate the content and attributes of these elements using JavaScript. This article will guide you through the essential properties and methods of the Pre object, accompanied by practical examples.

Understanding the <pre> Element

The <pre> tag is ideal for displaying code snippets, ASCII art, or any content where preserving formatting is critical. Unlike other HTML elements, text inside a <pre> tag will not have its whitespace collapsed, making it perfect for presenting structured text.

Accessing the <pre> Element

To interact with a <pre> element, you first need to access it through the Document Object Model (DOM). You can do this using methods like document.getElementById(), document.querySelector(), or others that retrieve elements from the DOM.

Here’s a basic example:

<pre id="myPre">
  This is some
  preformatted
  text.
</pre>

<script>
  const preElement = document.getElementById("myPre");
  console.log(preElement); // Output the HTMLPreElement
</script>

In this code:

  • We have a <pre> element with the id “myPre”.
  • In the JavaScript block, we use document.getElementById("myPre") to get the element.
  • The console.log() statement outputs the HTMLPreElement object, which represents the <pre> tag in the DOM.

Important Properties of the Pre Object

The Pre object inherits properties from the HTMLElement interface and offers specific properties that are useful when dealing with <pre> elements.

Property Type Description
`innerHTML` String Gets or sets the HTML content inside the `

` element. Includes any HTML tags within.
`innerText` String Gets or sets the text content of the `
` element, stripping out any HTML tags.
`textContent` String Similar to `innerText`, gets or sets the text content but preserves whitespace and is recommended for cross-browser compatibility.
`id` String Gets or sets the `id` attribute of the `
` element.
`className` String Gets or sets the value of the class attribute of the `
` element.
`style` Object An object that provides access to the inline styles of the `
` element.
`attributes` NamedNodeMap A collection of the HTML attributes of the `
` element.

Practical Examples

Let's delve into practical examples that illustrate how to use these properties:

1. Changing Text Content

The textContent property allows you to modify the content of the <pre> element dynamically:

<pre id="preContent">
  Original Text.
</pre>

<button id="changeButton1">Change Content</button>

<script>
  const preElementContent = document.getElementById("preContent");
  const changeButton1 = document.getElementById("changeButton1");

  changeButton1.addEventListener("click", () => {
    preElementContent.textContent = "New Text Content";
  });
</script>

In this code:

  • We have a <pre> element with id preContent
  • A button is added with id="changeButton1".
  • In the Javascript, when the button is clicked, we get preElementContent and change the textContent.

Clicking the button will update the content of the <pre> element.

2. Accessing and Modifying HTML Content

The innerHTML property lets you access and modify the HTML inside the <pre> element. You can inject HTML elements into the <pre> content.

<pre id="preHtml">
  <b>Bold</b> and <i>Italic</i> text.
</pre>

<button id="changeButton2">Add HTML</button>

<script>
  const preElementHtml = document.getElementById("preHtml");
  const changeButton2 = document.getElementById("changeButton2");

  changeButton2.addEventListener("click", () => {
    preElementHtml.innerHTML += "<br><mark>Highlighted text.</mark>";
  });
</script>

In this example:

  • The <pre> tag has the id attribute as preHtml.
  • There's a button to add HTML into the <pre> tag.
  • The event listener will add <br><mark>Highlighted text.</mark> to the content of <pre> tag when the button is clicked.

Clicking the "Add HTML" button adds highlighted text to the content of the <pre> tag.

3. Manipulating Styles

You can change the appearance of a <pre> element using the style property:

<pre id="preStyle">
  Styled Text.
</pre>

<button id="changeButton3">Change Style</button>

<script>
    const preElementStyle = document.getElementById('preStyle');
    const changeButton3 = document.getElementById("changeButton3")
    changeButton3.addEventListener("click", () => {
        preElementStyle.style.color = "white";
        preElementStyle.style.backgroundColor = "navy";
        preElementStyle.style.padding = "10px";
    });
</script>
  • We have a button with id changeButton3.
  • When the button is clicked, the event listener changes the background color, text color and padding of the <pre> tag.

Clicking the button changes the text color to white, background to navy, and adds 10px padding.

4. Accessing Attributes

Use the getAttribute() and setAttribute() methods to access and modify attributes of the <pre> element:

<pre id="preAttributes" data-info="Important">
  Attribute text.
</pre>

<button id="changeButton4">Change Attribute</button>

<script>
    const preElementAttributes = document.getElementById("preAttributes");
    const changeButton4 = document.getElementById("changeButton4")

    changeButton4.addEventListener("click", () => {
       preElementAttributes.setAttribute('data-info', 'Urgent');
        console.log(preElementAttributes.getAttribute('data-info')); // Output: Urgent
    });
</script>

In this example:

  • The <pre> element has data-info attribute.
  • Clicking the button changes the attribute of the <pre> tag.
  • The console.log displays the updated attribute value.

Clicking the button changes the data-info attribute to "Urgent", and the console shows the updated value.

5. Using innerText to get Content

The innerText property provides a way to access the text content of the <pre> element, stripping out any HTML tags. It also does not preserve whitespace, unlike textContent

<pre id="preInnerText">
  This is <b>bold</b> and
  <i>italic</i> text.
</pre>
<button id="displayButton">Display innerText</button>

<div id="displayDiv"></div>

<script>
  const preElementInnerText = document.getElementById("preInnerText");
  const displayButton = document.getElementById("displayButton");
  const displayDiv = document.getElementById('displayDiv');
  displayButton.addEventListener("click", () => {
      displayDiv.textContent = preElementInnerText.innerText;
  })
</script>

Here:

  • A <pre> tag is declared with content including HTML tags.
  • Clicking the button displays the plain text content of the <pre> tag into the div element, stripping any HTML tags.

Use Case Example: Code Viewer

A common use case for the <pre> tag is displaying code snippets. Here's a combined example that uses JavaScript to fetch code and display it inside a <pre> tag with highlighting:

<pre id="codeViewer"></pre>

<script>
    const codeViewer = document.getElementById('codeViewer');
    const codeSnippet = `
    function greet(name) {
      console.log('Hello, ' + name + '!');
    }

    greet('World');
    `;
    codeViewer.textContent = codeSnippet;
    codeViewer.style.backgroundColor = "#f0f0f0";
    codeViewer.style.padding = "10px";
    codeViewer.style.fontFamily = "monospace";
    codeViewer.style.overflow = "auto";
    codeViewer.style.whiteSpace = "pre-wrap";
</script>

Here:

  • A <pre> tag with id codeViewer is used to display the code.
  • The Javascript variable codeSnippet holds the code to display.
  • The codeSnippet is set to textContent of codeViewer element
  • Additional style properties are added to enhance the display.

This example shows how you can use the <pre> tag and the Pre object in JavaScript to create a basic code viewer.

Browser Support

The HTML Pre object is widely supported in all modern browsers, including:

  • Chrome
  • Firefox
  • Safari
  • Edge
  • Opera

This excellent browser support ensures that you can rely on the Pre object across various platforms and devices.

Conclusion

The HTML DOM Pre object provides a crucial interface for accessing and manipulating <pre> elements in JavaScript. With the properties and methods discussed in this guide, you can dynamically change the content, styles, and attributes of <pre> elements, enhancing your web pages with dynamic and user-friendly text displays. Understanding how to use the Pre object effectively is essential for any web developer working with content presentation, particularly for displaying code snippets and preformatted text.