Note that there are some explanatory texts on larger screens.

plurals
  1. POget text of an element without children in javascript
    primarykey
    data
    text
    <p>How do I get the text of an element without the children? Neither <code>element.textContent</code> nor <code>element.innerText</code> seem to be working.</p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;h1&gt;Test Heading&lt;/h1&gt; &lt;div&gt; Awesome video and music. Thumbs way up. Love it. Happy weekend to you and your family. Love, Sasha &lt;/div&gt; &lt;/body&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; fool("body"); &lt;/script&gt; </code></pre> <p>and here's the <code>fool</code> function:</p> <pre><code>jQuery.fn.justtext = function(text) { return $(this).clone() .children() .remove() .end() .text(); }; function fool(el) { reverse(el); function reverse(el) { $(el).children().each(function() { if($(this).children().length &gt; 0) { reverse(this); if($(this).justtext() != "") reverseText(this); } else { reverseText(this) } }); } function reverseText(el){ var text = el.textContent; var frag = text.toString().split(/ /); var foo = ""; var punctation_marks = [".",",","?","!"," ",":",";"]; for(i in frag){ if(punctation_marks.indexOf(frag[i]) == -1) foo += actualReverse(frag[i],punctation_marks) + " "; } el.textContent = foo; } function actualReverse(text,punctation_marks) { return (punctation_marks.indexOf(text.split("")[text.split("").length-1]) != -1)?text.split("").slice(0,text.split("").length-1).reverse().join("") + text.split("")[text.split("").length-1] : text.split("").reverse().join(""); } } </code></pre> <p><strong>edit</strong>: using <code>node.nodeType</code> doesn't really help and here's why: Imaginge the following HTML</p> <pre><code>&lt;td class="gensmall"&gt; Last visit was: Sat Mar 31, 2012 10:50 am &lt;br&gt; &lt;a href="./search.php?search_id=unanswered"&gt;View unanswered posts&lt;/a&gt; | &lt;a href="./search.php?search_id=active_topics"&gt;View active topics&lt;/a&gt; &lt;/td&gt; </code></pre> <p>if I'd use <code>nodeType</code>, only the text of the <code>a</code> element would change , but not the <code>td</code> itself ("last visit....")</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload