I am using Magento 2.2.1. I want to add a js file to change one special span tag content with CSS class "price" on the catalog page. I was using document.getelementnByClass.. for my js development. and my question is how to accept that in my Magento 2 project
2 Answers
You can use requireJs in your phtml File and use jquery for that
<script>
require([
'jquery',
], function ($) {
//here write your code :)
});
</script>
You can add JS files for the catalog page by layout method:
Add below code in catalog_product_view.xml file:
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<link src="Magento_Catalog::catalog_custom.js"/>
</head>
</page>
Then create catalog_custom.js file inside Catalog module at path view/frontend/web/js/catalog_custom.js
require([
'jquery'
], function ($) {
// your custom code
});
-
thanks for answering. one question arises. how can I add the js file to the module catalog and not change the vendor folder? I have a custom theme and I know working with it and as the same custom module.does it enough to add js file to {Theme_Dir}/Magento_Catalog/web/js ? Commented Aug 25, 2021 at 16:32
-
Yes, you need to add js file as same path {Theme_Dir}/Magento_Catalog/web/js Commented Aug 25, 2021 at 17:41
-
If this answer is useful for you then feel free to accept the answer. Commented Aug 25, 2021 at 17:55