skip to Main Content
<div
    data-global-messages="{&quot;addCartSuccessMessage&quot;:&quot;successfully added&quot;,&quot;creditRepresentativeMessage&quot;:&quot;Please contact your Credit Representative&quot;,&quot;nonStockMessage&quot;:&quot;Non-stock item&quot;,&quot;addWishlistSuccessMessage&quot;:&quot;Wish List.&quot;,&quot;itemExistsCartMessage&quot;:&quot;Please review error(s) below.&nbsp;&quot;,&quot;itemExistsWishlistMessage&quot;:&quot;Please review error(s) below.&nbsp;&quot;,&quot;nonAvailableMessage&quot;:&quot;substitute.&quot;,&quot;creditDepartmentMessage&quot;:&quot;Please contact Sea.&nbsp;&quot;}">
  </div>

How to get the attributes from above?

I tried document.querySelector('data-global-messages').getAttribute('addCartSuccessMessage') which returns null

2

Answers


  1. // Get the HTML element
    const divElement = document.querySelector('div[data-global-messages]');
    
    // Get the data-global-messages attribute as a string
    const dataGlobalMessages = divElement.getAttribute('data-global-messages');
    
    // Parse the string as JSON
    const dataAttributes = JSON.parse(dataGlobalMessages);
    
    // Access individual data attributes
    const addCartSuccessMessage = dataAttributes.addCartSuccessMessage;
    const creditRepresentativeMessage = dataAttributes.creditRepresentativeMessage;
    
    // Now, you can use these variables as needed
    console.log(addCartSuccessMessage);
    console.log(creditRepresentativeMessage);
    
    Login or Signup to reply.
  2. All data attributes are stored in the element’s dataset property.
    To access it you can do:

    const element = document.querySelector('div[data-global-messages]');
    const data = element.dataset.globalMessages;
    const json = JSON.parse(data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search