/    Sign up×
Community /Pin to ProfileBookmark

Custom function to get real first child element

[code]
function FCE(e) { // {{{
/* First Child Element – only tags, not text. */
e = e.firstChild;
do {
e = e.nextSibling;
} while (e && e.nodeType != 1);
return e;
} // }}}

window.onload = function() {
var li = document.getElementsByTagName(‘li’);
for (var i = 0; i < li[‘length’]; i++) {
console.log(li[i]); // Outputs <li>
console.log(li[i].firstChild); // Outputs <a href=…’>
console.log(FCE(li[i])); // Outpus null.
}
};

[/code]

The html is the traditional

[code]
<li><a href=’…>text</a></li>
[/code]

I just can’t understand what is wrong with the line

[code]
console.log(FCE(li[i]));
[/code]

Why is it returning null? The two lines above do return what is supposed to be returned, and I used them just as a test.

Also, the reason why I am trying the custom FCE(e) function, is that I want to be sure that the real first child element will be returned, and not, for instance, a text node or a “white space” node.

Any help would be appreciated.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@007JulienApr 16.2012 — Simply [I]<a href=...</a>[/I] has not sibling !
Copy linkTweet thisAlerts:
@FernandoBassoauthorApr 16.2012 — Simply [I]<a href=...</a>[/I] has not sibling ![/QUOTE]

But my funcion only tries finding a sibling if the element the first child itself is different than nodeType 1:

<i>
</i> e = e.firstChild;
do {
e = e.nextSibling;
} [B]while (e &amp;&amp; e.nodeType != 1);[/B]
return e;


If [B]e[/B] is already type 1, [B]e = e.nextSibling[/B] won't even run. The first child of <li> is <a>, but in my html I have some lines in which the <a> is after a newline character. That is why I'm trying to find the [B]real[/B] first child.
Copy linkTweet thisAlerts:
@KeverApr 16.2012 — You should use a 'while' loop instead of a 'do while' loop. The 'do while' will execute the code block once, before testing the condition.
×

Success!

Help @FernandoBasso spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...