While always deleting the last paragraph might be interesting, you'll sometimes want to delete something that's not at the end of the page. Scripts 12.5 and 12.6 make our code considerably more flexible, allowing the user to decide which paragraph is history, as shown in Figures 12.4 and 12.5 .
| 1. | nodeChangingArea = document. getElementById("modifiable"); As our HTML page now has multiple paragraphs, it could be confusing to keep track of which can and can't be deleted. Instead, we now set up an entirely new area: a div with the id of modifiable . Here, we set the global variable nodeChangingArea to that element node. |
| 2. | var delChoice = document. getElementById("grafCount"). selectedIndex; var allGrafs = nodeChangingArea. getElementsByTagName("p"); var killGraf = allGrafs.item (delChoice); When the user chose to delete a paragraph, they also had to pick which paragraph to delete. We read that number from the grafCount field and store it in delChoice . The allGrafs variable is then set to be all the paragraphs within nodeChangingArea , and the paragraph to be deleted is then stored in killGraf . |
| 3. | nodeChangingArea.removeChild (killGraf); This step is just like that in the previous task, except that when it's run we'll see paragraphs disappear from the middle of our page. |
-
Having trouble figuring out some of the other code? The nodeChanger() function combines (in order of appearance) functionality from Scripts 7.12, 3.12, and 7.4. It's very common in programming to have a library of simple routines, which, when put together, can create a single, much more complex whole.
-
Note that in the code above we're using nodeChangingArea where we previously used docBody when you're working with nodes, it's straightforward to swap out code that works with one element node for another. Here, we're looking at just one part of the page instead of the whole, but the overall way to accomplish our task is identical.
-
Instead of declaring nodeChangingArea as a global variable and initializing it in initAll() , we could have created and initialized it locally inside every function in which it's used. Each choice has its pros and cons; here, we went with the global so that we didn't have to initialize it over and over again.