Reputation: 3318
I need help resolving this error in IE9: "SCRIPT5007 Unable To get value of the property 'indexOf': object is null or undefined"
findParent = function (father, str, prop) {
/**
* Go up the DOM tree and find the parent element with the specified class or prop name.
* @param {Object} father - (HTMLElement)
* @param {String} str - the class of the father
* @param {string} prop - some other property such as name or id
* @example var parentEl = findParent(container, 'genericForm', 'name');
*/
'use strict';
if (prop === undefined || typeof prop !== 'string') {
prop = 'className';
}
while ((father !== undefined || typeof father !== 'string' || father !== null) && (father = father.parentElement) && !(father[prop].indexOf(str) >= 0));
return father;
};
var container = document.getElementById('description');
var parentEl = findParent(container, 'gForm', 'name');
alert(parentEl);
<form action="/gform.html" class="campaign-forms" method="post" name="gForm">
<fieldset class="fieldset" title="Type your question...">
<textarea name="description" id="description" placeholder="Type your question..." data-ana-label="Type your question..."></textarea>
<small class="error"><i class="close">×</i> This is a required field</small>
</fieldset>
</form>
I expect it to return the <form>
in this instance. Please help.
Upvotes: 0
Views: 1192
Reputation: 23406
It appears, that there's a difference between browsers. When father[prop]
is not explicitly defined, IE returns undefined
, other browsers seem to return an empty string.
To fix this you can detect undefined
and replace it with an empty string, something like this:
findParent = function (father, str, prop) {
'use strict';
if (prop === undefined || typeof prop !== 'string') {
prop = 'className';
}
while (father && (father = father.parentElement) && !((father[prop] || '').indexOf(str) >= 0));
^^^^^^^^^^^^^^^^^^^^
return father;
};
(I've just simplified the condition a bit, you can use the original father
-exists-detection if you want.)
Upvotes: 1