element.setAttribute is not a function when trying to set hrefIs there an “exists” function for jQuery?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How to change the href for a hyperlink using jQueryWhen to use double or single quotes in JavaScript?var functionName = function() vs function functionName() How to execute a JavaScript function when I have its name as a stringSetting “checked” for a checkbox with jQuery?Set a default parameter value for a JavaScript functionHow to decide when to use Node.js?Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Different meanings of こわい

What Exploit Are These User Agents Trying to Use?

How do I exit BASH while loop using modulus operator?

Implication of namely

Finitely generated matrix groups whose eigenvalues are all algebraic

How to Prove P(a) → ∀x(P(x) ∨ ¬(x = a)) using Natural Deduction

Using "tail" to follow a file without displaying the most recent lines

Why is the sentence "Das ist eine Nase" correct?

Sums of two squares in arithmetic progressions

How to coordinate airplane tickets?

Machine learning testing data

How obscure is the use of 令 in 令和?

Why are UK visa biometrics appointments suspended at USCIS Application Support Centers?

How to remove border from elements in the last row?

How to stretch the corners of this image so that it looks like a perfect rectangle?

How to prevent "they're falling in love" trope

Am I breaking OOP practice with this architecture?

How badly should I try to prevent a user from XSSing themselves?

Getting extremely large arrows with tikzcd

What historical events would have to change in order to make 19th century "steampunk" technology possible?

Placement of More Information/Help Icon button for Radio Buttons

How can a day be of 24 hours?

What does the same-ish mean?

What is the fastest integer factorization to break RSA?



element.setAttribute is not a function when trying to set href


Is there an “exists” function for jQuery?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How to change the href for a hyperlink using jQueryWhen to use double or single quotes in JavaScript?var functionName = function() vs function functionName() How to execute a JavaScript function when I have its name as a stringSetting “checked” for a checkbox with jQuery?Set a default parameter value for a JavaScript functionHow to decide when to use Node.js?Is there a standard function to check for null, undefined, or blank variables in JavaScript?













2















In order to avoid spam I've changed my link to a JavaScript function that decodes and sets the href when the link is clicked.



HTML:



<li><a id="email"><i class="fas fa-email"></i></a></li>


JS:



function decode(a) 
return a.replace(/[a-zA-Z]/g, function(c)
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
)


function openEmail(element)
var b = decode("DecodedMailToEmailAddress");
element.setAttribute("href", b);
element.setAttribute("onclick", "");
;

document.addEventListener('DOMContentLoaded', function ()
document.getElementById('email').addEventListener('click', openEmail);
);


But every time I click the link I get the following error:



TypeError: element.setAttribute is not a function


And it specifically points to:



element.setAttribute("href", b);


(And the line after that, if I put it first)



What am I doing wrong? I used the onClick HTML attribute before this to call the openEmail(this) function, but I'm trying to implement a Content Security Policy and that considers onClick as unsafe-inline.



Thanks!










share|improve this question



















  • 1





    Event handlers are passed an event object, not the element involved with the event.

    – Pointy
    Mar 21 at 20:36











  • You would need element.target (but calling an event object "element" is misleading, so pick a different name)

    – John Coleman
    Mar 21 at 20:40












  • @JohnColeman: That won't work if the icon inside the link is clicked.

    – Felix Kling
    Mar 21 at 20:43












  • @FelixKling Thanks for the warning. Would event.currentTarget be more reliable?

    – John Coleman
    Mar 21 at 20:45












  • @JohnColeman: Yep, that'd work.

    – Felix Kling
    Mar 21 at 20:48















2















In order to avoid spam I've changed my link to a JavaScript function that decodes and sets the href when the link is clicked.



HTML:



<li><a id="email"><i class="fas fa-email"></i></a></li>


JS:



function decode(a) 
return a.replace(/[a-zA-Z]/g, function(c)
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
)


function openEmail(element)
var b = decode("DecodedMailToEmailAddress");
element.setAttribute("href", b);
element.setAttribute("onclick", "");
;

document.addEventListener('DOMContentLoaded', function ()
document.getElementById('email').addEventListener('click', openEmail);
);


But every time I click the link I get the following error:



TypeError: element.setAttribute is not a function


And it specifically points to:



element.setAttribute("href", b);


(And the line after that, if I put it first)



What am I doing wrong? I used the onClick HTML attribute before this to call the openEmail(this) function, but I'm trying to implement a Content Security Policy and that considers onClick as unsafe-inline.



Thanks!










share|improve this question



















  • 1





    Event handlers are passed an event object, not the element involved with the event.

    – Pointy
    Mar 21 at 20:36











  • You would need element.target (but calling an event object "element" is misleading, so pick a different name)

    – John Coleman
    Mar 21 at 20:40












  • @JohnColeman: That won't work if the icon inside the link is clicked.

    – Felix Kling
    Mar 21 at 20:43












  • @FelixKling Thanks for the warning. Would event.currentTarget be more reliable?

    – John Coleman
    Mar 21 at 20:45












  • @JohnColeman: Yep, that'd work.

    – Felix Kling
    Mar 21 at 20:48













2












2








2








In order to avoid spam I've changed my link to a JavaScript function that decodes and sets the href when the link is clicked.



HTML:



<li><a id="email"><i class="fas fa-email"></i></a></li>


JS:



function decode(a) 
return a.replace(/[a-zA-Z]/g, function(c)
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
)


function openEmail(element)
var b = decode("DecodedMailToEmailAddress");
element.setAttribute("href", b);
element.setAttribute("onclick", "");
;

document.addEventListener('DOMContentLoaded', function ()
document.getElementById('email').addEventListener('click', openEmail);
);


But every time I click the link I get the following error:



TypeError: element.setAttribute is not a function


And it specifically points to:



element.setAttribute("href", b);


(And the line after that, if I put it first)



What am I doing wrong? I used the onClick HTML attribute before this to call the openEmail(this) function, but I'm trying to implement a Content Security Policy and that considers onClick as unsafe-inline.



Thanks!










share|improve this question
















In order to avoid spam I've changed my link to a JavaScript function that decodes and sets the href when the link is clicked.



HTML:



<li><a id="email"><i class="fas fa-email"></i></a></li>


JS:



function decode(a) 
return a.replace(/[a-zA-Z]/g, function(c)
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
)


function openEmail(element)
var b = decode("DecodedMailToEmailAddress");
element.setAttribute("href", b);
element.setAttribute("onclick", "");
;

document.addEventListener('DOMContentLoaded', function ()
document.getElementById('email').addEventListener('click', openEmail);
);


But every time I click the link I get the following error:



TypeError: element.setAttribute is not a function


And it specifically points to:



element.setAttribute("href", b);


(And the line after that, if I put it first)



What am I doing wrong? I used the onClick HTML attribute before this to call the openEmail(this) function, but I'm trying to implement a Content Security Policy and that considers onClick as unsafe-inline.



Thanks!







javascript dom-events






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 21 at 20:45









Felix Kling

562k131871937




562k131871937










asked Mar 21 at 20:35









jzegersjzegers

132




132







  • 1





    Event handlers are passed an event object, not the element involved with the event.

    – Pointy
    Mar 21 at 20:36











  • You would need element.target (but calling an event object "element" is misleading, so pick a different name)

    – John Coleman
    Mar 21 at 20:40












  • @JohnColeman: That won't work if the icon inside the link is clicked.

    – Felix Kling
    Mar 21 at 20:43












  • @FelixKling Thanks for the warning. Would event.currentTarget be more reliable?

    – John Coleman
    Mar 21 at 20:45












  • @JohnColeman: Yep, that'd work.

    – Felix Kling
    Mar 21 at 20:48












  • 1





    Event handlers are passed an event object, not the element involved with the event.

    – Pointy
    Mar 21 at 20:36











  • You would need element.target (but calling an event object "element" is misleading, so pick a different name)

    – John Coleman
    Mar 21 at 20:40












  • @JohnColeman: That won't work if the icon inside the link is clicked.

    – Felix Kling
    Mar 21 at 20:43












  • @FelixKling Thanks for the warning. Would event.currentTarget be more reliable?

    – John Coleman
    Mar 21 at 20:45












  • @JohnColeman: Yep, that'd work.

    – Felix Kling
    Mar 21 at 20:48







1




1





Event handlers are passed an event object, not the element involved with the event.

– Pointy
Mar 21 at 20:36





Event handlers are passed an event object, not the element involved with the event.

– Pointy
Mar 21 at 20:36













You would need element.target (but calling an event object "element" is misleading, so pick a different name)

– John Coleman
Mar 21 at 20:40






You would need element.target (but calling an event object "element" is misleading, so pick a different name)

– John Coleman
Mar 21 at 20:40














@JohnColeman: That won't work if the icon inside the link is clicked.

– Felix Kling
Mar 21 at 20:43






@JohnColeman: That won't work if the icon inside the link is clicked.

– Felix Kling
Mar 21 at 20:43














@FelixKling Thanks for the warning. Would event.currentTarget be more reliable?

– John Coleman
Mar 21 at 20:45






@FelixKling Thanks for the warning. Would event.currentTarget be more reliable?

– John Coleman
Mar 21 at 20:45














@JohnColeman: Yep, that'd work.

– Felix Kling
Mar 21 at 20:48





@JohnColeman: Yep, that'd work.

– Felix Kling
Mar 21 at 20:48












2 Answers
2






active

oldest

votes


















2














As Pointy mentions, the event handler is passed an event object, not an element.



Use this.setAttribute(...) instead. this refers to the element the handler is bound to.



Note that element.setAttribute("onclick", ""); won't remove the event handler you add via addEventListener, use removeEventListener instead:



function openEmail(element) 
var b = decode("DecodedMailToEmailAddress");
this.setAttribute("href", b); // or just this.href = b;
this.removeEventListener("click", openEmail);



You can learn more about event handling on quirksmode.org and MDN.






share|improve this answer























  • Thank you, it worked like a charm!

    – jzegers
    Mar 21 at 21:49


















0














Event handlers give a event property to the callback function. The element you're looking for can be found in event.target.



So the function becomes:



function openEmail(event) 
var b = decode("DecodedMailToEmailAddress");
event.target.setAttribute("href", b);
event.target.setAttribute("onclick", "");
;


By the way, you can also use event.target.href = … and setting event handers is better done with addEventListener instead of setting onclick, like you do in another part of your code.






share|improve this answer























  • This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

    – Felix Kling
    Mar 21 at 20:49











  • You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

    – edwin
    Mar 21 at 20:53












  • event.currentTarget and this would work.

    – Felix Kling
    Mar 21 at 20:54











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55288847%2felement-setattribute-is-not-a-function-when-trying-to-set-href%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














As Pointy mentions, the event handler is passed an event object, not an element.



Use this.setAttribute(...) instead. this refers to the element the handler is bound to.



Note that element.setAttribute("onclick", ""); won't remove the event handler you add via addEventListener, use removeEventListener instead:



function openEmail(element) 
var b = decode("DecodedMailToEmailAddress");
this.setAttribute("href", b); // or just this.href = b;
this.removeEventListener("click", openEmail);



You can learn more about event handling on quirksmode.org and MDN.






share|improve this answer























  • Thank you, it worked like a charm!

    – jzegers
    Mar 21 at 21:49















2














As Pointy mentions, the event handler is passed an event object, not an element.



Use this.setAttribute(...) instead. this refers to the element the handler is bound to.



Note that element.setAttribute("onclick", ""); won't remove the event handler you add via addEventListener, use removeEventListener instead:



function openEmail(element) 
var b = decode("DecodedMailToEmailAddress");
this.setAttribute("href", b); // or just this.href = b;
this.removeEventListener("click", openEmail);



You can learn more about event handling on quirksmode.org and MDN.






share|improve this answer























  • Thank you, it worked like a charm!

    – jzegers
    Mar 21 at 21:49













2












2








2







As Pointy mentions, the event handler is passed an event object, not an element.



Use this.setAttribute(...) instead. this refers to the element the handler is bound to.



Note that element.setAttribute("onclick", ""); won't remove the event handler you add via addEventListener, use removeEventListener instead:



function openEmail(element) 
var b = decode("DecodedMailToEmailAddress");
this.setAttribute("href", b); // or just this.href = b;
this.removeEventListener("click", openEmail);



You can learn more about event handling on quirksmode.org and MDN.






share|improve this answer













As Pointy mentions, the event handler is passed an event object, not an element.



Use this.setAttribute(...) instead. this refers to the element the handler is bound to.



Note that element.setAttribute("onclick", ""); won't remove the event handler you add via addEventListener, use removeEventListener instead:



function openEmail(element) 
var b = decode("DecodedMailToEmailAddress");
this.setAttribute("href", b); // or just this.href = b;
this.removeEventListener("click", openEmail);



You can learn more about event handling on quirksmode.org and MDN.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 21 at 20:42









Felix KlingFelix Kling

562k131871937




562k131871937












  • Thank you, it worked like a charm!

    – jzegers
    Mar 21 at 21:49

















  • Thank you, it worked like a charm!

    – jzegers
    Mar 21 at 21:49
















Thank you, it worked like a charm!

– jzegers
Mar 21 at 21:49





Thank you, it worked like a charm!

– jzegers
Mar 21 at 21:49













0














Event handlers give a event property to the callback function. The element you're looking for can be found in event.target.



So the function becomes:



function openEmail(event) 
var b = decode("DecodedMailToEmailAddress");
event.target.setAttribute("href", b);
event.target.setAttribute("onclick", "");
;


By the way, you can also use event.target.href = … and setting event handers is better done with addEventListener instead of setting onclick, like you do in another part of your code.






share|improve this answer























  • This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

    – Felix Kling
    Mar 21 at 20:49











  • You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

    – edwin
    Mar 21 at 20:53












  • event.currentTarget and this would work.

    – Felix Kling
    Mar 21 at 20:54















0














Event handlers give a event property to the callback function. The element you're looking for can be found in event.target.



So the function becomes:



function openEmail(event) 
var b = decode("DecodedMailToEmailAddress");
event.target.setAttribute("href", b);
event.target.setAttribute("onclick", "");
;


By the way, you can also use event.target.href = … and setting event handers is better done with addEventListener instead of setting onclick, like you do in another part of your code.






share|improve this answer























  • This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

    – Felix Kling
    Mar 21 at 20:49











  • You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

    – edwin
    Mar 21 at 20:53












  • event.currentTarget and this would work.

    – Felix Kling
    Mar 21 at 20:54













0












0








0







Event handlers give a event property to the callback function. The element you're looking for can be found in event.target.



So the function becomes:



function openEmail(event) 
var b = decode("DecodedMailToEmailAddress");
event.target.setAttribute("href", b);
event.target.setAttribute("onclick", "");
;


By the way, you can also use event.target.href = … and setting event handers is better done with addEventListener instead of setting onclick, like you do in another part of your code.






share|improve this answer













Event handlers give a event property to the callback function. The element you're looking for can be found in event.target.



So the function becomes:



function openEmail(event) 
var b = decode("DecodedMailToEmailAddress");
event.target.setAttribute("href", b);
event.target.setAttribute("onclick", "");
;


By the way, you can also use event.target.href = … and setting event handers is better done with addEventListener instead of setting onclick, like you do in another part of your code.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 21 at 20:48









edwinedwin

2,0781515




2,0781515












  • This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

    – Felix Kling
    Mar 21 at 20:49











  • You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

    – edwin
    Mar 21 at 20:53












  • event.currentTarget and this would work.

    – Felix Kling
    Mar 21 at 20:54

















  • This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

    – Felix Kling
    Mar 21 at 20:49











  • You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

    – edwin
    Mar 21 at 20:53












  • event.currentTarget and this would work.

    – Felix Kling
    Mar 21 at 20:54
















This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

– Felix Kling
Mar 21 at 20:49





This won't work if the user clicks on the icon inside the link (which they will do because the link contains no other child).

– Felix Kling
Mar 21 at 20:49













You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

– edwin
Mar 21 at 20:53






You're right. A solution is to use event.target.closest('a').setAttribute(…). This only works in modern browsers, though.

– edwin
Mar 21 at 20:53














event.currentTarget and this would work.

– Felix Kling
Mar 21 at 20:54





event.currentTarget and this would work.

– Felix Kling
Mar 21 at 20:54

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55288847%2felement-setattribute-is-not-a-function-when-trying-to-set-href%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현