vmars316 Posted October 23, 2020 Share Posted October 23, 2020 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 More sharing options...
dsonesuk Posted October 23, 2020 Share Posted October 23, 2020 (edited) If you want to change all anchor attributes using linkElements , why are you targeting .item[i] which does not exist? Edited October 23, 2020 by dsonesuk Link to comment Share on other sites More sharing options...
empressia Posted October 23, 2020 Share Posted October 23, 2020 (edited) 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_equalityhttps://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 October 23, 2020 by empressia Better formatting 1 Link to comment Share on other sites More sharing options...
vmars316 Posted October 23, 2020 Author Share Posted October 23, 2020 Thanks empressia ; You certainly have gone the extra mile . Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now