Tag Archives: DOM manipulation

Episode 10: If an Element Exists

How to tell if an element exists

When you’re working with jQuery, sometimes you need to figure out if an element that you’re trying to select actually exists on the page. You’d think this would be simple and straightforward, but there’s actually a little trick to it that I’ll share with you in this video.

We get started with a list of animals – one of them has a class of highlighted and elsewhere on the page, we want to create a little callout to put the highlighted animal in the spotlight.

We get started by adding a new element to the page using skills that we learned in Episode 3. Then we just add a few quick styles to the new element in CSS just so that we can see it on the page.

Next, we learn how to use jQuery text() method, both to add text to our new element and to fetch the text from another element. This works great as long as there’s an element on the page with the class of highlighted, but if it doesn’t exist, the page looks odd. We want to set up some different text if the highlighted class is missing from the page.

We talk just a bit about JavaScript and how to test if things are true. Many values in JavaScript aren’t actually strictly true or false, but rather truthy or falsey – in a sort of gray area. If a variable is empty and I test it, it returns falsey. Which means that if we test the variable where we used our selector, it should return falsey since it’s empty, right?

Well, not with jQuery. Because if a variable holds a jQuery selector, that variable is never actually empty because it holds a jQuery object. The jQuery object might be empty, but the variable doesn’t know that. It just knows it’s got a jQuery object so it returns a truthy value.

Huh?

Think of a jQuery object like a box. A box isn’t nothing – it’s definitely something. If you’re holding a box, then you’ve definitely got something in your hands. Now, that box might be empty or it might have a kitten or a pie in it. Either way, you’ve got something in your hands.

That’s how a jQuery object works. The jQuery object is something, even when it’s empty. So to test if an element that we’re trying to select is actually on the page, we have to test if the jQuery object is empty or not, not the variable where we used our selector.

We can test that by using the length property of the jQuery object to see if there’s anything in the box. If the length is greater than 0, then the box contains something. Otherwise, the box is empty.

Episode 8: Parents and Children

Parents and Children

While the title of this week’s video might sound like some sort of family therapy session, we’re actually going to be digging into a few of our methods for traversing the DOM – moving up the DOM with parent() or parents() and then moving down the DOM with children() or find().

There’s a lot of confusion and misunderstanding around these methods, so this week’s episode helps to clear that up. We start out with a document with lots of nested divs, each with a different background color just to make them easy to see.

First up, we take a look at parent() and parents(). The parent() method selects only one element – the direct parent element of the element we started from. The parents() method, on the other hand, will select all parent elements, including the <body> and the <html> elements.

But, with either the parent() or parents() methods, we’re able to add a selector and refine the selection that gets made. With the parent() method, that would select the parent element only in the event that it matches the selector. With the parents() method, you can filter out the elements that get selected – rather than selecting every single parent element all the way up to the <html> element, we can say exactly which elements should get selected.

Now that we understand parent() and parents(), let’s take a look at the differences between children() and find(). First up, the find() method requires a selector. If we need to select all the children elements nested inside the element we started from, then we can pass the universal selector (*) to the find() method, like this: find('*')

The children() method, on the other hand gets just the direct children. That throws a lot of people off, since it seems backwards. If we have parent() and parents(), shouldn’t we also have child() and children()?

But working our way up the DOM isn’t the same as working our way down. When we’re searching through ancestors, each element can have only one direct parent element. When we’re searching through descendants, each element could have 0, 1, or many direct children, plus additional descendants nested inside those children.

Just like with parents(), we can also pass a selector to children() to select only those direct children that match the selector rather than all of the direct children.

After working with our many nested divs page, we’ll take a look at a more real-world example – we have a block of content inside a div, with one paragraph that happens to be wrapped in a blockquote. Using our children() and find() methods, we see the difference between them quite clearly. Using the children() method, the paragraph inside the blockquote isn’t selected. But when we switch over to the find() method, we’re able to select that paragraph along with the others.

That’s a pretty good look into parent(), parents(), find(), and children(). Have fun experimenting with those methods to make sure you really understand the differences and next week we’ll take a look at adding animation to Simple Tabs example to make those tabs extra special.

Episode 6: jQuery Accordion

jQuery Accordion

In this video, we’ll walk through creating a simple content accordion. All of the sample content for the demo comes from Wikipedia.

Since we’ll be using a lot of special characters, we have to pay special attention to our charset meta tag to make sure all those special characters show up as expected rather than looking look a bunch of gobbledygook.

There are lots of different bits of HTML markup that can be used to create the HTML markup for an accordion, but I like to use a definition list (<dl>). I use the <dt> tags for the accordion titles and the <dd> tags for the accordion content areas. The <dd> tag can contain any other tags so the content can be quite complex, including headings, paragraphs, lists, images, videos, etc.

In this case, I’m making use of the new HTML <figure> and <figcaption> elements for presenting the photos and captions for each city. For the image captions, I’m using the captions provided by Wikipedia to ensure that the photographers are correctly credited for the use of their images.

Once we’ve got all of our content on the page, we’ll style that up with a bit of CSS to make it look like an accordion. After removing some of the browser’s default styles, we add a background color and some rounded corners to the titles and a border around the content areas.

Now we can see the page the way our site visitors who don’t have JavaScript enabled will see. The page looks nice, and these site visitors will never know they’re missing out on anything at all.

With the HTML and CSS out of the way, we can jump into the JavaScript. First up, we hide all of the <dd> tags to fold them out of the way. Then, we add a click handler to the <dt> tags that moves to the next <dd> tag and shows it when the <dt> is clicked.

That’s a bit of progress, but we have to add a bit more finesse to get it working like an accordion, like closing any other open panels when we click to open a new one. We make use some of the DOM traversal methods we used last time – next() and siblings(). We also make use of some of jQuery’s built-in animations – slideUp(), slideDown(), and slideToggle() – which we’ll be covering in detail in next week’s video.

Now that the basic accordion is working, we’ll apply some snazzy CSS and JavaScript techniques to write some special additional styles for the accordion to make it extra special and polished. We take a look at the famous body-class switching trick to write separate CSS styles depending on whether or not JavaScript is enabled. Using the body class, we write some extra CSS to make the <dt>‘s look and work a little more like buttons, and we add a class to the <dt> when they’re open so that the open panel can be styled a bit differently from the panels that are closed.

Pro Tip: Rather than adding color changes, sizes, borders and other CSS changes in your JavaScript, put style changes in your CSS file instead, and then just use JavaScript to add and remove CSS class names to control changes in style.

We’ll wrap up by making a few little optimizations – we toggle the ‘+’ and ‘-‘ characters to show if the panel is opened or closed, and style the <dd> content areas to match the orange color of the open titles. And we learn how to use a CSS3 transition to animate a background color change.

Creating a simple accordion is pretty simple – most of the work is in the CSS, and we use just a few lines of JavaScript to make it all work.

Episode 5: Traversing the DOM

Traversing the DOM

“Traversing the DOM” sounds kind of scary, but it’s just developer-speak for moving from one place in an HTML document to another. In this video, we’ll take a look at some of the methods jQuery provides for easily moving around.

Here, we’ll get started with a bunch of nested unordered lists so that we can learn how to move around from one list item to another. We’ll use jQuery’s addClass() method to add classes to the starting point and ending point(s) so that we can see how we’re moving around the document.

We’ll take a look at using the following methods:

  • next()
  • nextAll()
  • prev()
  • prevAll()
  • parent()
  • parents()
  • children()
  • find()
  • siblings()

In addition to those traversal methods, we’ll also look at how to use:

  • addClass()
  • first()

Learning how to move around an HTML document is a powerful tool to have in your toolbox. Once you’ve arrived at your endpoint, you can call any of jQuery’s methods to hide, show, animate, change CSS class names, replace content, etc. You’ll find that these methods are so universally helpful, that we’ll put them to work in nearly every tutorial we do.

As an example of how to put these methods to work, take a look at last week’s video on creating simple tabs without using a jQuery plugin.

Episode 3: Adding Content and Moving Content with jQuery

Adding and Moving Content with jQuery

In this video, we’ll take a look at all the different ways of adding content to a page using jQuery, whether we’re just adding some text, or if we’re adding new HTML elements to the page.

We’ll get started with a pretty simple HTML file – just a heading and a few paragraphs of text. To make that go by quickly, we take advantage of the Emmet package for Sublime Text.

Once the HTML document is ready to go, we’ll take a look at adding some text content to the page using a few different jQuery methods:

  • append()
  • prepend()
  • before()
  • after()

Once we learn how to use those, then we learn how to create new HTML elements with jQuery. Then we take a look at some jQuery methods for adding our newly created HTML elements to the page, using:

  • appendTo()
  • prependTo()
  • insertBefore()
  • insertAfter()

Next we learn a nicer way to create new HTML elements with jQuery, making the code more readable when we’re adding classes, id’s, text, and other attributes to the newly created elements.

Finally, we learn how to use these same methods to move existing content around the page so that it shows up in new spots. You can entirely re-arrange your HTML page by moving the content around, wherever you’d like.

Google+