Removing elements using jQuery is quite easy, but what happens when the elements we need to remove have children and we need to keep them intact? moreover, what happens when the elements we want to remove using jQuery are a list of elements with children to be kept? It’s easy too!
Following the image above, if we wanted to remove the a elements, leaving the img elements, all we need to do is to place this code inside your document.ready call
[js]
jQuery(‘.container’).children().map(function (index) {
jQuery(this).replaceWith(jQuery(this).contents());
});
[/js]
The call searches for all children of .container and runs the map function on them. Map is one of my favourite functions. It’s sort of a filter that you can apply to any given element. In this case, map will be applied to all the a elements inside .container because we used the children function, which only collects the first level children. Then, any mapped element will be replaced by its contents. We could use children again, just wanted to show another function. Contents, unlike children, will also collect any text nodes, so it will be perfect if you are already in a leaf node and want to remove it while keeping the text.
Isn’t it better to use the new(jquery 1.4) ‘unwrap’ method?
Of course it is, using unwrap involves one call. The downside is that jQuery 1.4 is quite recent. Even the internal bundled jQuery in WordPress 2.9 is 1.3.2. Some large sites make extensive use of jQuery versions prior to 1.3. If you can use 1.4 go ahead and use unwrap.
Great tutorial, thanks, will give it a try later.
wow! just what i was looking for!!! thanks again friend!
Exactly what I’ve been looking for!
thanks for good code and useful
A good way to strip out the li:s returned from the wp_list_pages function in wordpress.
Felix, I wouldn’t strip them out, since listing pages using ul li is a valid XHTML practice.
Not if you’re listing pages in a custom select box menu. 🙂
very great and powerful codes! and the site is quite very attractive too..thanks
Gorgeous!!! exactly what I needed.