Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #18740

Re: Clean up HTML content

Message-ID <2295376.vs5DUIPqoH@PointedEars.de> (permalink)
From Thomas 'PointedEars' Lahn <PointedEars@web.de>
Organization PointedEars Software (PES)
Date 2013-03-06 23:45 +0100
Subject Re: Clean up HTML content
Newsgroups comp.lang.javascript
References <kh4813$lkv$1@speranza.aioe.org> <2342178.BYbISWzQ9U@PointedEars.de> <kh5grn$bm0$1@speranza.aioe.org> <1699591.rPLLIT5s0r@PointedEars.de> <kh8ata$am8$1@speranza.aioe.org>

Show all headers | View raw


Cezary Tomczyk wrote:

> W dniu 2013-03-06 00:03, Thomas 'PointedEars' Lahn pisze:
>> Cezary Tomczyk wrote:
>>> W dniu 2013-03-05 17:55, Thomas 'PointedEars' Lahn pisze:
> [...]
>> What is usually frowned upon is posting uncommented source code that is
>> not self-explanatory, and maybe even badly formatted, because the poster
>> did not take care to understand it in the first place.  Your code is
>> neither.
> 
> I'll try to consider it while will be posting code next time. As for
> formatting, code was formatted, but for some reason do not know why here
> is unformatted.

I said: The code that you posted (IMHO) *is* self-explanatory, and _not_ 
badly formatted.  IOW, (IMHO) it is *OK* for posting even *without* 
additional comments.
 
> [...]
>>> Here's the code:
>>>
>>> var is_block_style = function (el) {
>>>       var el_style;
>>>       if (window.getComputedStyle) {
>>
>> You should feature-test this method in a way that does not primarily use
>> implicit type conversion.  There is one DOM implementation, MSHTML, that
>> is notorious for throwing strange exceptions on properties of type
>> "unknown" otherwise.  See also, e.g., jsx.object.isHostMethod().
   ^^^^^^^^^                             ^^^^^^^^^^^^^^^^^^^^^^^^^
> Yes, I know that IE return sometimes "object", sometimes "function".

More importantly, sometimes the result of the “typeof” operation is 
“"unknown"” there (I hope the additional quotes make it clear now).  And 
then a type-converting test throws an exception.  So a type-converting test 
cannot be considered appropriate for feature-testing host object's methods.  
It is insufficient for testing native object's methods already.

> However, I had never any problems with implicit type conversion like
> above.

Lucky you.

> One request: if you refer to some methods of your code, eg. e.g.,
> jsx.object.isHostMethod, then please also add link to source code. I
> guess it's coming from JSX project
> http://pointedears.de/websvn/listing.php?repname=JSX.
> 
> And you thought about that, right?

Yes …
 
> jsx.object.isMethodType = function (s) {
  ^^^^^^^^^^^^^^^^^^^^^^^
>    return /^\s*(function|object|unknown)\s*$/i.test(s);
> };

… and no; evidently the name of the method I mentioned is different.  The 
actual method *actually* is too long to be posted here.  It can be found in

<http://pointedears.de/websvn/filedetails.php?repname=JSX&path=%2Ftrunk%2Fobject.js>

which in turn can be easily found with a Web search.
 
>>>           el_style = window.getComputedStyle(el,
>>> null).getPropertyValue('display');
>>>       } else {
>>>           el_style = el.currentStyle.display;
>>>       }
>>>       return el_style;
>>> };
>>
>> You should generalize this code, see also jsx.dom.getComputedStyle().  In
> 
> I do not see here
> 
http://pointedears.de/websvn/filedetails.php?repname=JSX&path=%2Ftrunk%2Fdom.js
> method getComputedStyle.

Because it requires *CSS* (D)OM capabilities.  For historical reasons it is 
not available as jsx.dom.css.getComputedStyle(), though.

<http://pointedears.de/websvn/filedetails.php?repname=JSX&path=%2Ftrunk%2Fdom%2Fcss.js>

That, too, can be easily found with a Web search.

Try to be more careful in all respects, please.

>> this case, because the base object always is the same, you can even
>> safely perform the branching for the window.getComputedStyle() DOM method
>> – which should be document.defaultView.getComputedStyle() to be
>> compatible – only once.  You cannot assume, however, that if the
>> getComputedStyle() method is absent, the “currentStyle“ property must be
>> present; that is an inductive fallacy (hasty generalization).
> 
> Hm, both sources:
> 
> * https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

Keep in mind that this is a wiki.  Anyone logged in can write any nonsense 
there.  And anyone logged in can correct it.  If they learn about it.

> * http://msdn.microsoft.com/en-us/library/ie/ff975168%28v=vs.85%29.aspx
> 
> says about window.getComputedStyle. That's why I used this method.
> 
> However, when I look at David Mark method getKomputedStyle seems it's
> quite complicated :-(

So there *actually* *is* *more* than Firefox and Internet Explorer? ;-)

Seriously though, I remember to have observed several versions of Safari 4 
not having window.getComputedStyle() but 
document.defaultView.getComputedStyle().  The Gecko DOM, and the MSHTML 9 
DOM in Standards Mode, have both.

So far, document.defaultView.getComputedStyle() is the more standards-
compliant approach because:

1. “document” implements the “DocumentView” interface of W3C DOM Level 2
   Views [DOM2Views].

2. “document.defaultView” implements the “ViewCSS” interface of
   W3C DOM Level 2 Style CSS [DOM2CSS], which inherits from the
   “AbstractView” interface of [DOM2Views].

3. “getComputedStyle” is a method provided by “ViewCSS” interface. (ibid.)

(The reference to [HTML5] in [DOM2Views] appears to be a dead end here; the 
“Window” interface of [HTML5] does not provide a “getComputedStyle” method.)

______________
[DOM2Views] <http://www.w3.org/TR/DOM-Level-2-Views/> p.
[DOM2CSS]   <http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-ViewCSS>
[HTML5]     <http://www.w3.org/TR/html5/dom.html#the-document-object> pp.

>>> var imgClassName = 'testimg';
>>>
>>> var tidyHTML = function (node) {
>>>       var elms = node.childNodes,
>>>           i = elms.length,
>>>           text = '',
>>>           elm;
>>>
>>>       if (!node.hasChildNodes()
>>
>> I have never used that method before.  Unless you are sure about its
>> backwards-compatibility, you should replace the call with
> 
> I use https://developer.mozilla.org/en-US/docs/DOM/Node.hasChildNodes
> from long time. Sesms it's implemented long time ago. See:
> http://www.quirksmode.org/dom/w3c_core.html

It was *specified* a long time ago.  I rather do my own tests instead of 
relying on MDN or Quirks Mode.

>>>       && (node.nodeName.toLowerCase() === 'img'
>>> && !(new RegExp('(^|\\s)' + imgClassName +
>>         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>> '(\\s|$)')).test(node.className))) {
>>    ^^^^^^^^^^^
>> You should move or even generalize this code in order to leverage
>> caching.
> 
> Move new RegExp outside of method to do not creating new objects RegExp
> everytime?

Yes.

My next idea is that you can globally cache references to RegExp instances 
that do not have the “global” flag set.  But it is perhaps not applicable 
here.

>> You can do that because the RegExp does not have the “global” flag set
   ^^^^^^^^^^^^^^^
Meaning: “You can create the RegExp instance only once because …”

>> (i.e.,  its boolean ”global” property has the value “false”).
> 
> Right. I should set "global" as "true".

No, I did _not_ suggest that you should make that mistake:

  var rx = /foo/g;
  var s = "foo";

  /* true */
  rx.test(s)

  /* false */
  rx.test(s)

  /* true */
  rx.test(s)

  .
  .
  .
 
>>>           node.parentNode.removeChild(node);
>>>           return text;
>>>       }
>>>
>>>       while (i--) {
>>>           elm = elms[i];
>>
>> So AIUI you iterate backwards through the child nodes …
> 
> Yes.
> 
>>>           if (elm.nodeType === 1) {
>>
>> A strict comparison does not appear to be necessary or prudent here.  You
>> cannot know that the types match since you are dealing with a host
>> object. What you can know (from the ECMAScript Specification) is that
>> *if* the types match, it does not matter for the result or efficiency if
>> you use a strict comparison or not.  And you gain a little bit more
>> backwards-compatibility that way.
> 
> Yes, I remember your explanation from the past. But it's about JSLint
> which I do not remember now why JSLint require "===" all the time.
> 
>>>               text += tidyHTML(elm);
>>
>> … but why do you *append* to the “text” variable as if you had iterated
>> forwards, thereby reversing the order of the content?
> 
> Because sometimes I removing node.

How does that explain the opposite direction of the concatenation?

>> Equivalent code:
>>
>>    var a = ["foo", "bar", "baz"];
>>    var i = a.length;
>>    var a2 = [];
>>    while (i--)
>>    {
>>      if (a[i] != "bar")
>>      {
>>        a2.push(a[i]);
>>      }
>>    }
>>
>>    /* ["baz", "foo"] */
>>    console.log(a2);
>>
>> You are looking for something more like
>>
>>    for (var i = 0, len = elms.length; i < len; ++i)
>>    {
>>      text += tidyHTML(elms[i]);
>>    }
> 
> Not really. In short: I want to remove all html nodes, except img with
> specified class name + I need to care about formatting, eg. if text is
> in block element then I apply <br/> after plain text.

I am aware of that, but ISTM that you will still have to append/concatenate 
in the direction of the iteration or you will have the original content 
reduced *and* backwards.
 
>>>       }
>>>
>>>       if (typeof text !== 'undefined') {
>>
>> Again an unnecessary strict comparison.
> 
> JSLint case.

Learn how to configure it, or use a better tool.
 
>>>           if (is_block_style(node) === 'block') {
>>>               node.parentNode.insertBefore(document.createElement('br'),
>>> node.nextSibling);
>>>           }
>>
>> Why?  Usually it is misuse of the “br” element to use it as replacement
>> for a block delimiter.  Also, “display: block” does not necessarily mean
>> that there is a paragraph.  Consider, for example, positioned or floating
>> block elements.
> 
> Yes, I now saw the method getKomputedStyle from MyLibrary.

JFTR: You are not posting the URI of code you are referring to either.

> Unfortunately, it's quite complicated :/ I do not know about JSX similar
> method.

I seriously hope there is none.  What a bloat:

<https://github.com/cinsoft/My-Library/blob/master/mylib.asp#L2329>
 
-- 
PointedEars

Twitter: @PointedEars2
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Clean up HTML content Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2013-03-05 08:48 +0100
  Re: Clean up HTML content Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-03-05 17:55 +0100
    Re: Clean up HTML content Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2013-03-05 20:25 +0100
      Re: Clean up HTML content Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-03-06 00:03 +0100
        Re: Clean up HTML content Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-03-06 00:08 +0100
          Re: Clean up HTML content Dr J R Stockton <reply1300@merlyn.demon.co.uk.invalid> - 2013-03-06 22:06 +0000
            Re: Clean up HTML content Eric Bednarz <bednarz@fahr-zur-hoelle.org> - 2013-03-10 01:14 +0100
        Re: Clean up HTML content Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2013-03-06 22:02 +0100
          Re: Clean up HTML content Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-03-06 23:45 +0100
            Re: Clean up HTML content Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2013-03-09 11:29 +0100
              Re: Clean up HTML content Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-03-09 16:11 +0100
  Re: Clean up HTML content Danny <dann90038@gmail.com> - 2013-03-07 14:28 -0800
    Re: Clean up HTML content Cezary Tomczyk <cezary.tomczyk@gmail.com> - 2013-03-09 11:37 +0100
      Re: Clean up HTML content dann90038@gmail.com - 2013-03-09 11:44 -0800

csiph-web