Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Created November 14, 2024 13:40
Show Gist options
  • Select an option

  • Save maheshwaghmare/3f6762d82c2415da2800619c74d6ecba to your computer and use it in GitHub Desktop.

Select an option

Save maheshwaghmare/3f6762d82c2415da2800619c74d6ecba to your computer and use it in GitHub Desktop.

Revisions

  1. maheshwaghmare created this gist Nov 14, 2024.
    10 changes: 10 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    ```js
    // Example usage.
    import { parse } from '@wordpress/blocks'

    const parsedContent = parse( content, {
    __unstableSkipMigrationLogs: true,
    } )

    const blocks = findNestedBlocksByName( parsedContent, 'core/paragraph' );
    ```
    23 changes: 23 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    /**
    * Recursively search for blocks by name within a nested block structure.
    *
    * @param {Array} blocks - Array of blocks to search within.
    * @param {string} blockName - The block name to search for.
    * @returns {Array} - Array of blocks that match the specified name.
    */
    function findNestedBlocksByName(blocks, blockName) {
    let matchedBlocks = [];

    blocks.forEach(block => {
    if (block.name === blockName) {
    matchedBlocks.push(block);
    }

    // If the block has innerBlocks, recursively search within them
    if (block.innerBlocks && block.innerBlocks.length > 0) {
    matchedBlocks = matchedBlocks.concat(findNestedBlocksByName(block.innerBlocks, blockName));
    }
    });

    return matchedBlocks;
    }