JavaScript 2022

Term 3 Wednesday

May - July 2022

This site will be updated live during the sessions

Week 6 Exercise Xl

JavaScript

My pokemon

  • Chimchar
  • Mudkip
  • Mr Messy
  • Pikachu
  • Groudon
		
001function createNodeWithText(newNodeType, newNodeText)
		
002{
		
003	const newNode = document.createElement(newNodeType); // Create a new LI node       
		
004	const newText = document.createTextNode(newNodeText); // Create a new text node  
		
005	newNode.appendChild(newText); // Append text node to LI node 
		
006	return newNode;
		
007}
		
008
		
009
		
010function replaceNode(replacementNode, elemParent, textToBeReplaced ) {	
		
011	 
		
012	for (let i = 0; i < elemParent.children.length; i++) { // Loop through its child nodes
		
013		if (elemParent.children[i].innerText === textToBeReplaced) { // Check if element to be replaced exists 
		
014			elemParent.replaceChild(replacementNode, elemParent.children[i]); // If it does, replace it
		
015		}
		
016	}
		
017}
		
018
		
019window.onload = function() 
		
020{
		
021	const ulElement = document.getElementById('pokemon'); // Get the UL parent
		
022	const replacementNode = createNodeWithText("LI", "Squirtle");
		
023	replaceNode(replacementNode, ulElement, "Mr Messy");
		
024	
		
025	const newParagraphNode = createNodeWithText("P", "What is your favorite pokemon?");
		
026	
		
027	ulElement.insertAdjacentElement('afterend', newParagraphNode);
		
028	
		
029
		
030	
		
031}