Search code examples
javascriptjqueryhtmlcss-selectorsgetelementbyid

Setting a data attribute of an element based on its ID


I am trying to set the data-whatever attribute of this element:

<a
    class='btn-lg btn-success bg-primary'
    id='vsIDButton'
    data-toggle='modal'
    href='#messageModal'
    role='button'
    data-whatever=''>New Message</a>

Right now I managed to do it by replacing the whole element, but there should be a better way.

I have tried this and a few variations around this, using innerHTML:

const vSourceID="contact:7573981724739861"; 

document.getElementById("vsIDButton.attr('data-whatever')").innerHTML = vSourceID;

I have also tried this jQuery function I found in StackOverflow:

I have tried both this:

SetButton(vSourceID); 

function SetButton() {
    $('#vsIDButton > data-whatever').html();
}

And this:

SetButton(vSourceID);

function SetButton(x) {
    $('#vsIDButton > data-whatever').html(x);
}

Solution

  • You can do it like.

        let vSourceID="contact:7573981724739861"; 
        document.getElementById("vsIDButton").setAttribute('data-whatever', vSourceID);
    

    Make sure you are using unique id as vsIDButton

    OR

        SetButton(vSourceID);
        function SetButton(x) {
           $('#vsIDButton').attr('data-whatever',x);
        }