So I'm coding an html web page and am using the "translate" attribute in different parts of my code like so:
<div class="art-nav-outer">
<div class="art-nav-wrapper">
<div class="art-nav-inner">
<ul class="art-hmenu">
<li>
<a href="#">
<span class="l"></span>
<span class="r"></span>
<span class="t" translate="no">Introduction</span>
</a>
</li>
<li>
<a href="#" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t" translate="no">Content</span>
</a>
</li>
</ul>
</div>
</div>
</div>
I'm looping through the code using collectTextNodes($('body'));
.
This is the function declaration:
function collectTextNodes(element){
for (var child= element.firstChild; child!==null; child= child.nextSibling) {
if(child.nodeType === 3 && ...)
//doaction
else if(child.nodeType === 1)
collectTextNodes(child);
}
}
What I would like to do is add a condition to the 'if' which says:
'if the attribute "translate" of the child node is NOT "no"' or 'if the child node does NOT have the attribute "translate"'
then do action
I know there aren't any node Object properties or methods that will return this, but I can't figure what line to write to retrieve it or if it's even possible.
The idea for me is to know when a text needs to be translated or not when searching through the nodes.
Any kind of help or advice is appreciated.
I found the solution.
The issue is that when writing:
function collectTextNodes(element){
for (var child= element.firstChild; child!==null; child= child.nextSibling) {
if(child.nodeType === 3 && ...)
//doaction
else if(child.nodeType === 1)
collectTextNodes(child);
}
}
child.nodeType == 3 returns true for all text nodes and child.hasAttribute("translate") searches if this node has an attribute "translate" but if it's a text node then it won't have any attributes and if it does have the attribute then it won't be a text. In that case the if condition will never be satisfied.
The correct solution is:
function collectTextNodes(element, texts){
for (var child= element.firstChild; child!==null; child= child.nextSibling) {
if (child.nodeType === 3)
{
texts.push(child);
}
else if (child.nodeType === 1)
{
if(!(child.hasAttribute('translate') && $(child).attr('translate') == "no"))
{
collectTextNodes(child, texts);
}
}
}
}
In this case if the node is an element and this element has an attribute "translate" and the attribute "translate" == "no" then go further down the tree to it's child, else move on to it's next sibling.