Is it possible to get Magento attribute values on product page when writing custom java script code?

I am working on a frontend script where i need access to the product sku to check some logic i am writing.

2 Answers 2


I think the below will show you a few elements of how to build your solution to render product attribute using javascript. The method that pulls the product attribute is not in this answer so that the answer is to the point.

the phtml template


/* @var $block \Magento\Framework\View\Element\Template */
/* @var $viewModel \Mbs\ProductAttribute\ViewModel\ProductAttributeViewModel */
/** @var \Magento\Framework\Escaper $escaper */

$viewModel = $block->getData('viewModel');

<div id="material-container-no-js">
    <!-- Magento conventional way to render an product attribute -->
    <?php echo $escaper->escapeHtml($viewModel->getProductAttributeText('material')); ?>

<!-- Magento javascript way to render an product attribute -->
<div id="material-container">
    I will show the material in a second

<script type="text/x-magento-init">
        "#material-container": {
            "Mbs_ProductAttribute/js/show_attribute": {
                "material": "<?php echo $escaper->escapeHtml($viewModel->getProductAttributeText('material')); ?>"

the javascript file

], function ($) {
    'use strict';

    return function(config, element) {
        $(element).html('The material for this product is ' + config.material)

full code here: https://bitbucket.org/magstaging/productattribute/src/master/


Since the JS script should only run on the frontend and is quite simple i decided to solve it just as simple by getting the value from the div where the SKU is located using this code:

<script type="text/javascript">

const skuDiv = document.getElementsByClassName("sku")
const skuItem = skuDiv[0].innerText
const skuCurrentItemSlice = skuItem.slice(4)

Simple and works perfect for just getting the SKU value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.