// Example usage.
import { parse } from '@wordpress/blocks'
const parsedContent = parse( content, {
__unstableSkipMigrationLogs: true,
} )
const blocks = findNestedBlocksByName( parsedContent, 'core/paragraph' );
Created
November 14, 2024 13:40
-
-
Save maheshwaghmare/3f6762d82c2415da2800619c74d6ecba to your computer and use it in GitHub Desktop.
Gutenberg | Find blocks by block name - Recursively search for blocks by name within a nested block structure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment