0

I would like to select all elements with direct text contents. So given the document

<div>
 <h1>Hi</h1>
 <article>
   <p>blah balah blah</p>
   <p>blah blahrg blarg</p>
 </article>
 <footer></footer>
</div>

I would like to select the h1 and p elements (so 3 elements total). Is there a simple way to do this?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
George Mauer
  • 117,483
  • 131
  • 382
  • 612

2 Answers2

3
(function(){
    var ignoredNodes = {
    "script" : true,
    "noscript" : true
    };

    jQuery("*", "body").filter(
        function(){
        var c;

        if( this.nodeName.toLowerCase() in ignoredNodes ) {
        return false;
        }

        c = this.firstChild;

        return c && c.nodeType === 3 && jQuery.trim(c.data);
        }
    );

    //[<h1>Hi</h1>, <p>blah balah blah</p>, <p>blah blahrg blarg</p>]
})()
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • I am not sure if `c.data` is cross-browser, there is also a `nodeValue` property that has the text content. The trim is required to filter out empty text nodes, such are created when you have newline after div – Esailija Oct 16 '11 at 23:26
  • nice one Esailija , I guess that he'll want to remove all non semantic elements like – alonisser Oct 16 '11 at 23:51
  • nice catch @alonisser, feature added :) – Esailija Oct 16 '11 at 23:56
  • It still works fine for me even at this page. If the `nodeType` returned is 1 for a given `node`, it's a regular html tag and you need to access `childNodes` of the given `node` to see text nodes(`nodeType 3`). – Esailija Oct 17 '11 at 00:08
  • thanks for the clarification @Esailija- glad to learn something new! – alonisser Oct 17 '11 at 00:12
1

I think this was answered here: How do I select text nodes with jQuery? with both jquery and pure javascript solutions

Community
  • 1
  • 1
alonisser
  • 11,542
  • 21
  • 85
  • 139