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?
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With