Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

In JavaScript, the Attribute object provides properties for working with attributes within the HTML elements. Here is a list of all the Attribute object’s properties.

Property Use
isId Yields true if the attribute is an Id; otherwise, yields false
name Gets the name of the attribute
value Gets or sets the value of the attribute
specified Yields true if the attribute has been specified; otherwise, yields false

Creating and appending elements

To create a new element in an HTML document, use the document.create
Element()
method. When you use createElement(), a new beginning and end tag of the type you specify will be created.

Here’s an example of how you can use this method to dynamically create a list in an HTML document from an array.

 Generating a list


 

Here are some types of balls

Removing elements

For all the great things that it lets you do with HTML documents, the HTML DOM is not highly regarded by professional JavaScript programmers. It has a number of oddities and tends to make some things more difficult than they should be.

One of the big faults with the DOM is that it doesn’t provide any way to directly remove an element from a document. Instead, you have to tell the DOM to find the parent of the element you want to remove and then tell the parent to remove its child. It sounds a little confusing, but this example should clear it all up.

 Remove an element
 


 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum molestie pulvinar ante, a volutpat est sodales et. Ut gravida justo ac leo euismod, et tempus magna posuere. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer non mi iaculis, facilisis risus et, vestibulum lorem. Sed quam ex, placerat nec tristique id, mattis fringilla ligula. Maecenas a pretium justo. Suspendisse sit amet nibh consectetur, tristique tellus quis, congue arcu. Etiam pellentesque dictum elit eget semper. Phasellus orci neque, semper ac tortor ac, laoreet ultricies enim.

When you run this code in a browser and press the button, the onclick event calls the removeFirstParagraph() function.

The first thing removeFirstParagraph() does is to select the element that you actually want to remove, the element with the id = firstparagraph. Then, the script selects the parent node of the first paragraph. It then uses the removeChild() method to remove the first paragraph.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: