Search code examples
javascripthtmlattributes

How to use setAttribute to an element in code with {}?


How can I attribute such code to a html tag?

It's a attr ===>>> data-kt-drawer-activate="{default: true, lg: false}"

I tried the following method but I get an error:

newAside.setAttribute("data-kt-drawer-activate", "{default: true, lg: false}" );

Solution

  • On this current page, I ran your code as below:

    let newAside= document.querySelector("#question > div > div.postcell.post-layout--right > div.mb0 > div")
        newAside.setAttribute("data-kt-drawer-activate", "{default: true, lg: false}" );
    console.log(newAside)
    
    output: <div class="mt16 d-flex gs8 gsy fw-wrap jc-end ai-start pt4 mb16" data-kt-drawer-activate="{default: true, lg: false}">...         
    
    
    

    so setting attribute part of your code works. I think problem occurs when you are selecting the element