I've I'm getting a href value from a loaded AJAX page: and every time I load an AJAX page, it gets the value from the newly loaded page.
I use this to get the right href value:
firstURL = l[0].childNodes[0].attributes[0].nodeValue;
However, on the last page, this node does not exist (because we're on the last page), and returns:
Uncaught TypeError: Cannot read property 'attributes' of undefined trans.js:393
(anonymous function) trans.js:393
j jquery.min.js:2
k.fireWith jquery.min.js:2
x jquery.min.js:4
(anonymous function)
Is there a way for me to assign this variable, if the child node l[0].childNodes[0].attributes[0].nodeValue exists?
You can check if there is a child node before trying to access it:
var firstURL = '';
if(l[0].childNodes.length > 0){ // only if there's more than 1 child node
firstURL = l[0].childNodes[0].attributes[0].nodeValue;
}
Side notes:
childNodes includes text nodes so you might prefer children which only contains elements and no text nodes. If in future you add any text before the target, you will grab the text node instead.getAttribute('href') instead of getting the first attribute that exists.To use .getAttribute() you would just replace the .attributes[0] like so:
firstURL = l[0].childNodes[0].getAttribute('href');
This would be more robust because if you ever add new attributes to the element, this will survive the change, whereas relying on it always being the first could cause problems.
Also note that if you use getAttribute() then you don't need to access the nodeValue, because the actual attribute value is returned directly by getAttribute()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With