Reputation: 421
I have a slight problem in the code regarding the if condition check for DOM element, the requirement is that I should not allow 'BR' tag to pass
function testclick(handler) {
var nodeList = handler.childNodes;
for (var item in nodeList) {
if (typeof (nodeList[item].tagName) !== 'undefined') {
if (typeof (nodeList[item].tagName !== 'BR')) {
alert(nodeList[item].tagName);
}
}
}
}
the working Jsfiddle is here http://jsfiddle.net/ganesh_vellanki/agana62d/6/
can some one suggest where I went wrong
Thanks for time
Upvotes: 2
Views: 79
Reputation: 239693
When you do
typeof (nodeList[item].tagName) !== 'BR'
you are actually checking the type of the result of the expression
nodeList[item].tagName !== 'BR'
which will be a boolean object and it will considered truthy always. That is why your code doesn't skip BR tags. Instead, you might want to compare the tagName
with BR
like this
if (nodeList[item].tagName && nodeList[item].tagName.toUpperCase() !== 'BR') {
alert(nodeList[item].tagName);
}
This converts the tagName
to upper case and then compares it with BR
. If they both are different, then it allows the alert to be executed.
Upvotes: 1
Reputation: 24648
You don't need typeof
. This is the updated fiddle.
Code:
function testclick(handler) {
var nodeList = handler.childNodes;
for (var item in nodeList) {
var tagName = nodeList[item].tagName;
if (tagName !== 'BR' && tagName != undefined) {
console.log(tagName);
}
}
}
Upvotes: 1
Reputation: 4751
Try this:
function testclick(handler) {
var nodeList = handler.childNodes;
for (var item in nodeList) {
var tagName = nodeList[item].tagName !== undefined ? nodeList[item].tagName.toLowerCase() : null;
if (tagName !== null && tagName !== 'br') {
alert(tagName);
}
}
}
http://jsfiddle.net/agana62d/8/
Upvotes: 2