Jump to content

Need help: getAttribute and setAttribute


vmars316
 Share

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 comment
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 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
 Share

×
×
  • Create New...