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 comment
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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...