Targeting single page with JS

Here, the code operates on anything that matches the #searchButton element:

jQuery("#searchButton")

If there is a searchButton on other pages, it will match it, soo you need to be more specific.

For example, on the homepage, the <body> tag will have the home class, here is my sites homepage body tag:

<body class="home blog logged-in admin-bar no-customize-support">

So to make it target only the search button on the home page, you could try something like this:

jQuery(".home #searchButton")

Alternatively, only enqueue the JS on that particular page, but the selector method is superior. Make sure there is only one element on the page with that ID as IDs need to be unique

Leave a Comment