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>
<html>
<head>
</head>
<body>

<h4>getElementByTagName-ChangeBlankToSelf.html</h4>

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

<p>getElementByTagName-ChangeBlankToSelf.html</p>

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

<script>
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")
        }
}
}
</script>

</body>
</html>

I like the new Forum look ,

Thanks for your Help...

Link to post
Share on other sites

Hi!

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.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality

 

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

https://jsbin.com/minufujiba/1/edit?html,js,console,output

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.

Guest
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.

Loading...
×
×
  • Create New...