• Skip to primary navigation
  • Skip to main content
Matthew Dunbar

Matthew Dunbar

Hire Me
  • About
  • Portfolio
  • Blog
    • General
    • HTML
    • jQuery
    • PHP
    • Optimization
  • Hire Me
You are here: Home / Archives for jQuery

jQuery

How to Remove an Element from a Page Using jQuery

February 5, 2017

The Description

Have you ever had an element in your template that you need to remove on a specific page? Or remove an element from all pages except home? With jQuery, tackling this annoyance is much more simple than you’d expect.

In this example, we have a YouTube video in an iframe element that is designed into the template header. Because it’s in the header, it’s appearing on every page, and while CSS can hide the element, it still loads on the page before the CSS loads (slowing down page speed).

To remove the YouTube iframe on any page that’s not the homepage, we will use jQuery’s .remove() feature and use a simple javascript if/else statement to target the element on a specific page.

In this case, we will target the body tag and if it has the class .home in it, it will do nothing and if the body tag doesn’t have .home, it will execute the .remove() function on the targeted element.

Let’s explore the code below.

The jQuery



<script>
$(document).ready(function() {
	if ($("body").hasClass("home")) { 
		// Doing nothing here
		} else {
		$("#ytplayer").remove(); }
	});  
});
</script>


Now, when we inspect element on any page that doesn’t have .home in the body tag, we will notice the element is completely missing from the template. And since YouTube embeds can take up a considerable load time, removing it from any page that doesn’t need it is ideal.

Filed Under: jQuery

  • « Go to Previous Page
  • Page 1
  • Interim pages omitted …
  • Page 4
  • Page 5
  • Page 6
  • Page 7
  • Page 8
  • Go to Next Page »
© 2025 Matthew Dunbar - All Rights Reserved Back to Top