SteveC
SteveC

Reputation: 371

How to set an attribute with a blank value?

When I use the following:

myElement.setAttribute('data-title', title);

where title is blank I don't get a blank attribute. I get an attribute with no value.

Is there a way to get the blank attribute using either JavaScript or jQuery? I ask because if I can't then the code I have that references the attribute later is going to become complex to deal with the possibility of there being no value.

Upvotes: 1

Views: 2669

Answers (2)

user2226755
user2226755

Reputation: 13159

setAttribute is native function.

var myElement = document.getElementById("myId");

myElement.setAttribute('data-title', "")

myElement.getAttribute('data-title'); // you get : ""

myElement.getAttribute('data-test'); // you get : null


if (myElement.getAttribute('data-title') !== "" && myElement.getAttribute('data-title') !== null)
    console.log("not empty");

If you want to use jQuery prefere, attr :

var $myElement = $("#myId");

$myElement.attr("data-title", "");

$myElement.attr("data-title"); // you get : ""

$myElement.attr("data-test"); // you get : undefined

if (myElement.getAttribute('data-title') !== "" && typeof(myElement.getAttribute('data-title')) !== "undefined")
    console.log("not empty");

Upvotes: 1

Alvaro Silvino
Alvaro Silvino

Reputation: 9733

You should use attr

like:

myElement.attr('data-ttitle','')

to retrieve:

var data = myElement.attr('data-ttitle')

reference here

Upvotes: 1

Related Questions