3 Matching Annotations
  1. Jul 2022
  2. Jun 2022
    1. Highlight part of an element This example uses the Range.setStart() and Range.setEnd() methods to add part of an address to a range. The selected range is then highlighted using Range.surroundContents(). The address contains nine nodes: five text nodes, and four <br> elements.

      ```html

      Wyatt Earp<br> 101 E. Main St.<br> Dodge City, KS<br> 67801<br> USA


      Nodes in the original address:

        ```

        ```js const address = document.getElementById('address'); const log = document.getElementById('log');

        // Log info address.childNodes.forEach(node => { const li = document.createElement('li'); li.textContent = ${node.nodeName}, ${node.nodeValue}; log.appendChild(li); });

        // Highlight the street and city const startOffset = 2; // Start at third node: 101 E. Main St. const endOffset = 5; // End at fifth node: Dodge City, KS const range = document.createRange(); range.setStart(address, startOffset); range.setEnd(address, endOffset);

        const mark = document.createElement('mark'); range.surroundContents(mark); ```