If I have html like this:
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
I'm trying to use .text() to retrieve just the string "This is some text", but if I were to say $('#list-item').text(), I get "This is some textFirst span textSecond span text".
Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?
The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written.
I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.
Code provided for easy reference:
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
Simple answer:
$("#listItem").contents().filter(function(){
return this.nodeType == 3;
})[0].nodeValue = "The text you want to replace with"
This seems like a case of overusing jquery to me. The following will grab the text ignoring the other nodes:
document.getElementById("listItem").childNodes[0];
You'll need to trim that but it gets you what you want in one, easy line.
EDIT
The above will get the text node. To get the actual text, use this:
document.getElementById("listItem").childNodes[0].nodeValue;
Easier and quicker:
$("#listItem").contents().get(0).nodeValue
Similar to the accepted answer, but without cloning:
$("#foo").contents().not($("#foo").children()).text();
And here is a jQuery plugin for this purpose:
$.fn.immediateText = function() {
return this.contents().not(this.children()).text();
};
Here is how to use this plugin:
$("#foo").immediateText(); // get the text without children
isn't the code:
var text = $('#listItem').clone().children().remove().end().text();
just becoming jQuery for jQuery's sake? When simple operations involve that many chained commands & that much (unnecessary) processing, perhaps it is time to write a jQuery extension:
(function ($) {
function elementText(el, separator) {
var textContents = [];
for(var chld = el.firstChild; chld; chld = chld.nextSibling) {
if (chld.nodeType == 3) {
textContents.push(chld.nodeValue);
}
}
return textContents.join(separator);
}
$.fn.textNotChild = function(elementSeparator, nodeSeparator) {
if (arguments.length<2){nodeSeparator="";}
if (arguments.length<1){elementSeparator="";}
return $.map(this, function(el){
return elementText(el,nodeSeparator);
}).join(elementSeparator);
}
} (jQuery));
to call:
var text = $('#listItem').textNotChild();
the arguments are in case a different scenario is encountered, such as
<li>some text<a>more text</a>again more</li>
<li>second text<a>more text</a>again more</li>
var text = $("li").textNotChild(".....","<break>");
text will have value:
some text<break>again more.....second text<break>again more
Try this:
$('#listItem').not($('#listItem').children()).text()
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
$($('#listItem').contents()[0]).text()
Short variant of Stuart answer.
or with get()
$($('#listItem').contents().get(0)).text()
I presume this would be a fine solution also - if you want to get contents of all text nodes that are direct children of selected element.
$(selector).contents().filter(function(){ return this.nodeType == 3; }).text();
Note: jQuery documentation uses similar code to explain contents function: https://api.jquery.com/contents/
P.S. There's also a bit uglier way to do that, but this shows more in depth how things work, and allows for custom separator between text nodes (maybe you want a line break there)
$(selector).contents().filter(function(){ return this.nodeType == 3; }).map(function() { return this.nodeValue; }).toArray().join("");
jQuery.fn.ownText = function () {
return $(this).contents().filter(function () {
return this.nodeType === Node.TEXT_NODE;
}).text();
};
If the position index of the text node is fixed among its siblings, you can use
$('parentselector').contents().eq(index).text()
This is an old question but the top answer is very inefficient. Here's a better solution:
$.fn.myText = function() {
var str = '';
this.contents().each(function() {
if (this.nodeType == 3) {
str += this.textContent || this.innerText || '';
}
});
return str;
};
And just do this:
$("#foo").myText();
I propose to use the createTreeWalker to find all texts elements not attached to html elements (this function can be used to extend jQuery):
function textNodesOnlyUnder(el) {
var resultSet = [];
var n = null;
var treeWalker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, function (node) {
if (node.parentNode.id == el.id && node.textContent.trim().length != 0) {
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_SKIP;
}, false);
while (n = treeWalker.nextNode()) {
resultSet.push(n);
}
return resultSet;
}
window.onload = function() {
var ele = document.getElementById('listItem');
var textNodesOnly = textNodesOnlyUnder(ele);
var resultingText = textNodesOnly.map(function(val, index, arr) {
return 'Text element N. ' + index + ' --> ' + val.textContent.trim();
}).join('\n');
document.getElementById('txtArea').value = resultingText;
}
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
<textarea id="txtArea" style="width: 400px;height: 200px;"></textarea>
I wouldn't bother with jQuery for this, especially not the solutions that make unnecessary clones of the elements. A simple loop grabbing text nodes is all you need. In modern JavaScript (as of this writing — "modern" is a moving target!) and trimming whitespace from the beginning and end of the result:
const { childNodes } = document.getElementById("listItem");
let text = "";
for (const node of childNodes) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.nodeValue;
}
}
text = text.trim();
Live Example:
const { childNodes } = document.getElementById("listItem");
let text = "";
for (const node of childNodes) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.nodeValue;
}
}
console.log(text);
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
Some people would use reduce for this. I'm not a fan, I think a simple loop is clearer, but this usage does update the accumulator on each iteration, so it's not actually abusing reduce:
const { childNodes } = document.getElementById("listItem");
const text = [...childNodes].reduce((text, node) =>
node.nodeType === Node.TEXT_NODE ? text + node.nodeValue : text
, "").trim();
const { childNodes } = document.getElementById("listItem");
const text = [...childNodes].reduce((text, node) =>
node.nodeType === Node.TEXT_NODE ? text + node.nodeValue : text
, "").trim();
console.log(text);
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
Or without creating a temporary array:
const { childNodes } = document.getElementById("listItem");
const text = Array.prototype.reduce.call(childNodes, (text, node) =>
node.nodeType === Node.TEXT_NODE ? text + node.nodeValue : text
, "").trim();
const { childNodes } = document.getElementById("listItem");
const text = Array.prototype.reduce.call(childNodes, (text, node) =>
node.nodeType === Node.TEXT_NODE ? text + node.nodeValue : text
, "").trim();
console.log(text);
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
Using plain JavaScript in IE 9+ compatible syntax in just a few lines:
const childNodes = document.querySelector('#listItem').childNodes;
if (childNodes.length > 0) {
childNodesLoop:
for (let i = 0; i < childNodes.length; i++) {
//only target text nodes (nodeType of 3)
if (childNodes[i].nodeType === 3) {
//do not target any whitespace in the HTML
if (childNodes[i].nodeValue.trim().length > 0) {
childNodes[i].nodeValue = 'Replacement text';
//optimized to break out of the loop once primary text node found
break childNodesLoop;
}
}
}
}
Get all text in an element without text in any child elements still seems non trivial to do in 2022.
No jQuery needed though.
To get all raw textNode(s) content:
const getElementTextWithoutChildElements = (el) =>
Array.from(el.childNodes) // iterator to array
.filter(node => node.nodeType === 3) // only text nodes
.map(node => node.textContent) // get text
.join('') // stick together
;
Or similar, using reduce:
const getElementTextWithoutChildElements = (el) =>
[].reduce.call(
el.childNodes,
(a, b) => a + (b.nodeType === 3 ? b.textContent : ''),
''
);
Should work with this:
<div>
you get this
<b>not this</b>
you get this too
</div>
will return:
you get this
you get this too
Whitespace between elements could be tricky, suggest using with .trim() and/or normalize all whitespace, e.g.
For debugging and logging to quickly identify elements I find this is usually enough:
getElementTextWithoutChildElements(...).replace(/\s+/g, ' ').trim();
// 'you get this you get this too'
Though you might want to tweak whitespace differently, perhaps within the reduce() function itself to handle whitespace per node.
e.g. whitespace handling per node:
const getElementTextWithoutChildElements_2 = (el) =>
Array.from(el.childNodes)
.filter(node => node.nodeType === 3)
.map(node => node.textContent.trim()) // added .trim()
.join(',') // added ','
;
Quick tests for things above:
document.body.innerHTML = `
you get this
<b>not this</b>
you get this too
`;
// '\n you get this\n <b>not this</b>\n you get this too\n'
getElementTextWithoutChildElements(document.body);
// '\n you get this\n \n you get this too\n'
getElementTextWithoutChildElements(document.body).replace(/\s+/g, ' ').trim();
// 'you get this you get this too'
getElementTextWithoutChildElements_2(document.body);
// 'you get this,you get this too'
This is a good way for me
var text = $('#listItem').clone().children().remove().end().text();
I came up with a specific solution that should be much more efficient than the cloning and modifying of the clone. This solution only works with the following two reservations, but should be more efficient than the currently accepted solution:
You are getting only the text
The text you want to extract is before the child elements
With that said, here is the code:
// 'element' is a jQuery element
function getText(element) {
var text = element.text();
var childLength = element.children().text().length;
return text.slice(0, text.length - childLength);
}
Live demo
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
<input id="input" style="width: 300px; margin-top: 10px;">
<script type="text/javascript">
$("#input").val($("#listItem").clone().find("span").remove().end().text().trim());
//use .trim() to remove any white space
</script>
For beginners:
I preferred #DUzun's answer because it's simple to understand and more efficient than the accepted answer. But it only partially worked for me as you can't directly pass the element with a class selector like this
$(".landing-center .articlelanding_detail").get(0).immediateText() //gives .immediateText is not a function error
or this
$(".landing-center .articlelanding_detail")[0].immediateText() //gives .immediateText is not a function error
because once you extract the native Element by using [index] or .get(index) out of the $() function you loose jQuery Object methods chainability as mentioned here. And most of the solutions are only in context to ids, not so elegant to use multiple times for the elements with a class selectors.
So, I wrote jQuery plugin:
$.fn.mainText = function(x=0) {
return $.trim(this.eq(x).contents().not(this.eq(x).children()).text().replace(/[\t\n]+/g,' '));
};
This will return the text of the element irrespective of if ids or class are used as selectors excluding child elements. Also will remove any \t or \n to get a clean string.
Use it like this:
Case 1
$("#example").mainText(); // get the text of element with example id
Case 2
$(".example").mainText(); // get the text of first element with example class
Case 3
$(".example").mainText(1); // get the text of second element with example class and so on..
Alternative version of the answere without JQuery
[...document.getElementById("listItem").childNodes].find(c => c.nodeType === Node.TEXT_NODE).nodeValue
Just like the question, I was trying to extract text in order to do some regex substitution of the text but was getting problems where my inner elements (ie: <i>, <div>, <span>, etc.) were getting also removed.
The following code seems to work well and solved all my problems.
It uses some of the answers provided here but in particular, will only substitute the text when the element is of nodeType === 3.
$(el).contents().each(function() {
console.log(" > Content: %s [%s]", this, (this.nodeType === 3));
if (this.nodeType === 3) {
var text = this.textContent;
console.log(" > Old : '%s'", text);
regex = new RegExp("\\[\\[" + rule + "\\.val\\]\\]", "g");
text = text.replace(regex, value);
regex = new RegExp("\\[\\[" + rule + "\\.act\\]\\]", "g");
text = text.replace(regex, actual);
console.log(" > New : '%s'", text);
this.textContent = text;
}
});
What the above does is loop through all the elements of the given el (which was simply obtained with $("div.my-class[name='some-name']");. For each inner element, it basically ignores them. For each portion of text (as determined by if (this.nodeType === 3)) it will apply the regex substitution only to those elements.
The this.textContent = text portion simply replaces the substituted text, which in my case, I was looking for tokens like [[min.val]], [[max.val]], etc.
This short code excerpt will help anyone trying to do what the question was asking ... and a bit more.
Not sure how flexible or how many cases you need it to cover, but for your example, if the text always comes before the first HTML tags – why not just split the inner html at the first tag and take the former:
$('#listItem').html().split('<span')[0];
and if you need it wider maybe just
$('#listItem').html().split('<')[0];
and if you need the text between two markers, like after one thing but before another, you can do something like (untested) and use if statements to make it flexible enough to have a start or end marker or both, while avoiding null ref errors:
var startMarker = '';// put any starting marker here
var endMarker = '<';// put the end marker here
var myText = String( $('#listItem').html() );
// if the start marker is found, take the string after it
myText = myText.split(startMarker)[1];
// if the end marker is found, take the string before it
myText = myText.split(endMarker)[0];
console.log(myText); // output text between the first occurrence of the markers, assuming both markers exist. If they don't this will throw an error, so some if statements to check params is probably in order...
I generally make utility functions for useful things like this, make them error free, and then rely on them frequently once solid, rather than always rewriting this type of string manipulation and risking null references etc. That way, you can re-use the function in lots of projects and never have to waste time on it again debugging why a string reference has an undefined reference error. Might not be the shortest 1 line code ever, but after you have the utility function, it is one line from then on. Note most of the code is just handling parameters being there or not to avoid errors :)
For example:
/**
* Get the text between two string markers.
**/
function textBetween(__string,__startMark,__endMark){
var hasText = typeof __string !== 'undefined' && __string.length > 0;
if(!hasText) return __string;
var myText = String( __string );
var hasStartMarker = typeof __startMark !== 'undefined' && __startMark.length > 0 && __string.indexOf(__startMark)>=0;
var hasEndMarker = typeof __endMark !== 'undefined' && __endMark.length > 0 && __string.indexOf(__endMark) > 0;
if( hasStartMarker ) myText = myText.split(__startMark)[1];
if( hasEndMarker ) myText = myText.split(__endMark)[0];
return myText;
}
// now with 1 line from now on, and no jquery needed really, but to use your example:
var textWithNoHTML = textBetween( $('#listItem').html(), '', '<'); // should return text before first child HTML tag if the text is on page (use document ready etc)
Use an extra condition to check if innerHTML and innerText are the same. Only in those cases, replace the text.
$(function() {
$('body *').each(function () {
console.log($(this).html());
console.log($(this).text());
if($(this).text() === "Search" && $(this).html()===$(this).text()) {
$(this).html("Find");
}
})
})
http://jsfiddle.net/7RSGh/
To be able to trim the result, use DotNetWala's like so:
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text()
.trim();
I found out that using the shorter version like document.getElementById("listItem").childNodes[0] won't work with jQuery's trim().
just put it in a <p> or <font> and grab that $('#listItem font').text()
First thing that came to mind
<li id="listItem">
<font>This is some text</font>
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
You can try this
alert(document.getElementById('listItem').firstChild.data)
I am not a jquery expert, but how about,
$('#listItem').children().first().text()
This untested, but I think you may be able to try something like this:
$('#listItem').not('span').text();
http://api.jquery.com/not/
This question builds on an answer provided in How to wrap word into span on user click in javascript.
In my example, the user can double-click on any word to wrap it in a span element, but b/c this is based on splitting on whitespace, it won't work if the word is followed by punctuation.
HTML:
<div class="color-coding">
<span class="orange color-coding">Hello world this is some text.</span>
<br>
<span class="orange color-coding">Here is some more!</span>
</div>
JS:
jQuery(document).ready(function($) {
$('.color-coding').dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var sword = $.trim(range.toString());
if(sword.length)
{
var newWord = "<span class='highlight'>"+sword+"</span>";
$(this).each(function(){
$(this).html(function( _, html ) {
return html.split(/\s+/).map(function( word ) {
return word === sword ? newWord : word;
}).join(' ');
});
});
}
range.collapse();
e.stopPropagation();
});
});
I could add punctuation detection for the split, but that would of course remove the punctuation, and I need to retain it, so using the following won't meet my needs:
html.split(/\s+|[.,-\/#!$%\^&\*;:{}=\-_`~()]/)
Fiddle: http://jsfiddle.net/b11nxk92/3/
execCommand
Perfect solution for evergreen browsers:
if(sword.length) {
this.setAttribute('contenteditable','true');
document.execCommand("insertHTML", false, "<span class='highlight'>"+sword+"</span>");
this.removeAttribute('contenteditable');
}
This solution, toggles the container to editable mode, then trigger a command to insert the new html code. See: https://msdn.microsoft.com/en-us/library/hh801231(v=vs.85).aspx#inserthtml and https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
Fiddle: http://jsfiddle.net/b11nxk92/6/
RegExp
Also, I love RegExp so I made this solution.
if (sword.length) {
$(this).each(function(){
$(this).html(function( _, html ) {
return html.replace(
new RegExp("([^\\w]|^)("+sword+")([^\\w]|$)","g"),
"$1<span class='highlight'>$2</span>$3"
);
});
});
}
Instead of using split and then join the regular expression selects three elements (a non word character or the begining) + (our word) + (a non word character or the end) then using $ you choose where to keep it.
Fiddle: http://jsfiddle.net/b11nxk92/4/
I want to add a class (and later on to send that string to php) to a text with javascript. Whenever I try to do that, the code is adding the class to the first occurrence of my selection, not to the actual selection. Keep in mind that I want to send that EXACT selection to php (and put it in a database as well so it keep that class even after refresh).
JQ
$("#highlight").click(function(){
paraval = $('#para').html();
sel = window.getSelection();
newst = '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(sel, newst);
$('#para').html(newvalue);
});
HTML
<p>Will only highlight if text is selected from comment class div only</p>
<div class="comment" id="para" contenteditable="true">Here goes some text Here goes some text Here goes some text Here goes some text
Some other text</div>
<input type="button" value="Highlight" id="highlight"/>
CSS
.selectedText{
background-color:yellow;
}
.comment{
border: solid 2px;
}
.comment::selection {
background-color: yellow;
}
example here: http://jsfiddle.net/zq1dqu3o/3/
try to select the last occurrence of the word "text". the first one will get the class "selectedText"...
thanks
Call me lazy, but if you don't mind span being you selection marker tag, you can use rangy's cssApplier class.
var cssApplier;
$(document).ready(function() {
rangy.init();
cssApplier = rangy.createCssClassApplier(
"selectedText", {normalize: true,
applyToEditableOnly:true});
});
$("#highlight").click(function(){
if(cssApplier != undefined)
{
cssApplier.toggleSelection();
}
});
I use applyToEditableOnly here to make it only work in that specific div. (I'm not sure how cross-browser compatible that particular setting is. Worked in Chrome and Firefox though.) This uses position rather than selection text to decide what to mark.
JS Fiddle Here: http://jsfiddle.net/zq1dqu3o/7/
You can get the last occurence with lastIndexOf() and proceed like this:
$("#highlight").click(function(){
paraval = $('#para').text();
sel = "text";
var n = paraval.lastIndexOf(sel);
var before = paraval.substring(0,n);
newst = before + '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(paraval, newst);
$('#para').html(newvalue);
});
Just created a fiddle for it: Replacing last occurence
Note: This quick example is only working because the word you want to highlight is at the last position of the text, but you can check out if this solution is ok for your request. In case the last occurence of the word is elsewhere, just create a variable "after" that contains the text following the last occurence of the word to the end.
Have just provided an example for this in updated fiddle: Replacing last occurence update
with following update to previous code:
var after = paraval.substring(n + sel.length, paraval.length);
newst = before + '<a class="selectedText">' + sel + '</a>' + after;
I have a html code that cannot be altered directly.
<span class="class1 class2 class3 "> First name*: </span>
I need to move the * at the begining or the text. The end result should be this:
<span class="class1 class2 class3 "> *First name: </span>
I also need to make the * to be red (I need to add a class only for this character).
Any ideas?
I'd suggest:
$('span.class1.class2.class3').text(function(i, t){
/* i is in the index of the current element among those returned,
t is the text of the current element.
We return the new text, which is an asterisk, followed by the original text,
with the asterisk removed (using replace to replace the asterisk with an empty string):
*/
return '*' + t.replace(/\*/,'');
});
JS Fiddle demo.
If, however, you need a more generic approach (for example if you have multiple elements with the same/similar selectors):
// selects all the span elements, and filters:
$('span').filter(function(){
// discards the elements that *don't* have '*:' in their text:
return $(this).text().indexOf('*:') > -1;
// iterates over those elements (as above):
}).text(function(i, t) {
return '*' + t.replace(/\*/,'');
});
JS Fiddle demo.
In order to 'make it red,' you'd have to manipulate the HTML, rather than just the text, of the element:
$('span').filter(function(){
return $(this).text().indexOf('*:') > -1;
// Using 'html()' to set the HTML of the 'span' element:
}).html(function(i, h) {
// creating a span and prepending to the current element
return '<span class="required">*</span>' + h.replace(/\*/,'');
});
Coupled with the CSS:
.required {
color: red;
}
JS Fiddle demo.
Further, for simplicity, given that you want to target the * with a class-name (and therefore wrap it in an element-node), you could avoid the string-manipulation and simply float:
$('span').html(function(i,h){
// simply wrapping the `*` in a span (using html() again):
return h.replace(/(\*)/,'<span class="required">*</span>');
});
With the CSS:
.required {
float: left;
color: red;
}
JS Fiddle demo.
References:
filter().
html().
text().
If the problem is the very specific scenario you gave,
$(".class1.class2.class3").each(function() {
var inner = $(this).html();
$(this).html("*" + inner.replace("*",""));
}
var span = $('span.class1.class2.class3');
var new_text = span.text().replace(/\*/, '').replace(/^(\s*)/, '\1<span style="color:red;">*</span>');
span.html(new_text);
Demo
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/
I think I found myself a solution, a bit funny :
if($.trim($('#test').html()).substr(0,4).toLowerCase() == "<h2>")
{
$('#test h2:first').css('background-color', 'red');
}
What do you think about? :)
You can use .contents to conditionally ignore leading nodes that are only whitespace text. Then see if the first node is an <h2> (Fiddle):
function isFirstChildH2(selector) {
// get th efirst node, which may be a text node
var firstNode = $(selector).contents().first();
// if the first node is all whitespace text, ignore it and go to the next
if(firstNode[0].nodeType == 3 && firstNode.text().match(/\S/g) == null) {
firstNode = firstNode.next();
}
if(firstNode.is("h2")) {
// it's an h2; do your magic!
alert("h2 is the first thing on " + selector)
} else {
// first node is either non-whitespace text or an non-h2 element
// don't do your magic
alert("h2 is NOT the first thing on " + selector)
}
}
isFirstElementH2("#test");
The challenge we're facing here is that javascript recognizes whitespace as a text node as well. Therefore, from a javascript point of view, this HTML:
<div id="test">
<h2>Try 1</h2>
Test Test Test
<h2>Try 2</h2>
</div>
Is different from this HTML:
<div id="test"><h2>Try 1</h2>
Test Test Test
<h2>Try 2</h2>
</div>
In the first case, the first node inside the div is a textNode (nodeType == 3)
In the second HTML example, the first node inside the div is a h2 node.
I've come up with a solution for this, a handy function that loops through all elements combining jQuery and native javascript.
Solution
var objNodes = $(".wrapper").contents().get();
function loopNodes(objNodes, i) {
i = (typeof i === "undefined") ? 0 : i;
if (objNodes[i].nodeType !== 3) {
return {"isHeader":true, "first":$(objNodes[i])};
} else {
var strText = objNodes[i].innerText || objNodes[i].textContent;
if ($.trim(strText).length === 0) {
return loopNodes(objNodes, i+1);
} else {
return {"isHeader":false, "first":null};
}
}
}
Usage
var objResults = loopNodes(objNodes);
if (objResults.isHeader) {
console.log("Coolness");
objResults.first.text("AWESOME FIRST HEADER!");
} else {
console.log("Less Coolness");
}
In action:
http://jsbin.com/welcome/61883/edit
Edit: Added the cross-browser way of getting innerText/textContent. See Quirksmode for full reference on the matter.
OK, let's mix some jQuery with plain DOM code (as jQuery is not capable of handling text nodes):
var $el = $("#test > h2:first-child");
if (!$el.length) return false;
var el = $el.get(0),
reg = /\S/; // no whitespace
for (var prev = el; prev = prev.previousSibling; )
if (prev.nodeType == 3 && reg.test(prev.data))
return false;
return el;
Demo at jsfiddle.net