Jump to content

Need help: getAttribute and setAttribute

Recommended Posts

Tia  ;

Getting errors

getElementByTagName-ChangeBlankToSelf.html:24 Uncaught TypeError: Cannot read property 'getAttribute' of undefined
    at ChangeBlankToSelf (getElementByTagName-ChangeBlankToSelf.html:24)
    at HTMLButtonElement.onclick (getElementByTagName-ChangeBlankToSelf.html:17)

with the following code

<!DOCTYPE html>


<a href="https://www.w3schools.com" target="_blank">Visit W3Schools</a>
<a href="https://www.w3schools.com" target="_blank">Visit W3Schools</a>


<button onclick="ChangeBlankToSelf()">Change_Blank To _Self</button>

function ChangeBlankToSelf(){
  var linkElements , i;
  linkElements = document.getElementsByTagName("a");
  for (i = 0; i < linkElements.length; i++) {
        if (linkElements.item[i].getAttribute("target") = "_blank") 
           linkElements.item[i].setAttribute("target", "_self")


I like the new Forum look ,

Thanks for your Help...

Link to post
Share on other sites


item is a function, not an object, so you must call it:

linkElements.item(i).setAttribute("target", "_self")

By the way, getElementsByTagName returns HTMLCollection and you can get single item also in this way:

linkElements[i].setAttribute("target", "_self")

Finally, you incorrectly compare whether the target equals _blank. You used "=" which means you are assigning this value. You must use "==" or "===" operator.  Please refer to the MDN documentation.



Corrected code and additionally the same example in ES6+ syntax :)


Edited by empressia
Better formatting
  • Like 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...