Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an element (h2) is really the first element inside a div?

I want to "manage" the first h2 element inside a div, only if it's really the "first element"

<div id="test">
    <h2>Try 1</h2>
    Test Test Test
    <h2>Try 2</h2>
</div>  

here only h2 with text "Try 1" must be managed

<div id="test">
    Test Test Test
    <h2>Try 1</h2>
    <h2>Try 2</h2>
</div>  

Here no (there is text before).

How can I do it with jQuery?

like image 810
markzzz Avatar asked Dec 12 '22 19:12

markzzz


2 Answers

No jquery needed for that, just take:

document.getElementById('test').firstChild.nodeName // gives the name of the node

This will give you the name of the very first node, even if it's not a tag but just a plain text-node!

optionally you could of course use document.querySelector() if you want to be more flexible with your selectors and know that most of the clients browser support it.

To be clear: if you add a newline, this will also be considered as a text-node, so the heading needs to start on the same line or you will get #text as result for both examples!

This will fail:

<div id="test">
    <h2>Try 1</h2>
    Test Test Test
    <h2>Try 2</h2>
</div>

and this will work:

<div id="test"><h2>Try 1</h2>
    Test Test Test
    <h2>Try 2</h2>
</div>

a little demo for you

like image 164
Christoph Avatar answered Apr 13 '23 00:04

Christoph


This is how you would filter to get only the header that is the first node, ignoring all blank text nodes:-

$("#test").children("h2").first().filter(function() {

    var childNodes = this.parentNode.childNodes;
    var i = 0;
    var textNode = 3;

    // No children
    if(!childNodes.length) {
        return false;
    }

    // Skip blank text node
    if(childNodes[i].nodeType === textNode && childNodes[i].textContent.trim().length === 0) {
        i ++;
    }

    // Check we have a match
    return childNodes[i] === this;

});

Here is it in action http://jsfiddle.net/nmeXw/

like image 29
Stuart Wakefield Avatar answered Apr 12 '23 22:04

Stuart Wakefield