Skip to content

Instantly share code, notes, and snippets.

@0187773933
Created December 11, 2022 14:12
Show Gist options
  • Save 0187773933/61116cfe2ce14bdd2f2af009e53c4263 to your computer and use it in GitHub Desktop.
Save 0187773933/61116cfe2ce14bdd2f2af009e53c4263 to your computer and use it in GitHub Desktop.
Javascript - Traverse Down through A DOM Node
let prompt_elements = [ ...document.querySelectorAll( ".stack__answer-question" )[ 0 ].querySelectorAll( "p" ) ];
let tree_walker = document.createTreeWalker( prompt_elements[ 2 ] , NodeFilter.SHOW_ALL , {
acceptNode: function ( node ) {
return NodeFilter.FILTER_ACCEPT;
}
} , false );
let done = false;
while( done === false ) {
let next_node = tree_walker.nextNode();
if ( !next_node ) { done = true; }
console.log( next_node );
}
@0187773933
Copy link
Author

0187773933 commented Dec 11, 2022

function apply_to_all_child_nodes( starting_element , x_function ) {
	let tree_walker = document.createTreeWalker( starting_element , NodeFilter.SHOW_ALL , {
		acceptNode: function ( node ) {
			return NodeFilter.FILTER_ACCEPT;
		}
	} , false );
	let done = false;
	while( done === false ) {
		let next_node = tree_walker.nextNode();
		if ( !next_node ) { done = true; }
		x_function( next_node );
	}
}
apply_to_all_child_nodes( document.getElementById( "test-1" ) , function( node ) {
	if ( !node ) { return; }
	if ( node === null ) { return; }
	if ( !node.attributes ) { return; }
	[ ...node.attributes ].forEach( attr => node.removeAttribute( attr.name ) );
	node.classList = "";
	switch( node.localName ) {
		case "li":
			break;
		case "input":
			// console.log( "why the fuck are there inputs here ?" );
			node.parentNode.removeChild( node );
		default:
			break;
	}
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment