Use Cheerio to strip out any attributes we used to keep track of our work, then generate new HTML. This also closes any tags we opened but did not close.
438150
function cleanup(html) {
      html = cheerio.load(html);
      html('[' + ignoreAttr + ']').removeAttr(ignoreAttr);
      html = html.html();
      return html;
    }
411780
function parseScript(html) {
	var $ = cheerio.load(html);
	$('script').each((i, elem) => {
		var $script = $(elem);
		var $section = $script.parents('section');
		$section.attr('data-script', encodeURIComponent($script.html()));
		$script.remove();
	})
	return $.html();

}
1283742
def create
      @tag = Tag.new(params[:tag])

      respond_to do |format|
        if @tag.save
          format.html { redirect_to @tag, notice: 'Tag was successfully created.' }
          format.json { render json: @tag, status: :created, location: @tag }
        else
          format.html { render action: "new" }
          format.json { render json: @tag.errors, status: :unprocessable_entity }
        end
      end
    end
1060641
function () {
            var self = this;
            if (!self.isChildrenFiltered) {
                var writer = new (module.require('html-parser/writer/basic'))();
                self._writeChildrenHTML(writer);
                var parser = new (module.require('html-parser/parser'))(writer.getHtml()), children = parser.parse().childNodes;
                self.empty();
                util.each(children, function (c) {
                    self.appendChild(c);
                });
                self.isChildrenFiltered = 1;
            }
        }
82926
function (out) {
            if (this._cfgOk) {
                this._domId = this._createDynamicId();
                var tagName = this._cfg.type;
                var markup = ['<', tagName, ' id="', this._domId, '"'];
                if (this._cfg.attributes) {
                    markup.push(' ' + ariaUtilsHtml.buildAttributeList(this._cfg.attributes));
                }
                markup.push('></' + tagName + '>');
                out.write(markup.join(''));
            }
        }
923907
def render_tag(tag, attrs=None, content=None, close=True):
    
    builder = "<{tag}{attrs}>{content}"
    if content or close:
        builder += "</{tag}>"
    return format_html(
        builder,
        tag=tag,
        attrs=mark_safe(flatatt(attrs)) if attrs else "",
        content=text_value(content),
    )
1222440
def html_factory(tag, **defaults):
    '''

    '''
    def html_input(*children, **params):
        p = defaults.copy()
        p.update(params)
        return Html(tag, *children, **p)
    return html_input
89134
def close( self ):
        """"""

        if self.tag in self.parent.twotags:
            self.parent.content.append( "</%s>" % self.tag )
        elif self.tag in self.parent.onetags:
            raise ClosingError( self.tag )
        elif self.parent.mode == 'strict_html' and self.tag in self.parent.deptags:
            raise DeprecationError( self.tag )
954788
def clean(self):
        
        # Calls handle_starttag, handle_endtag, and handle_data
        self.feed()

        # Clean up any parent tags left open
        if self.current_parent_element['tag'] != '':
            self.cleaned_html += '</{}>'.format(self.current_parent_element['tag'])

        # Remove empty <p> added after lists
        self.cleaned_html = re.sub(r'(</[u|o]l>)<p></p>', r'\g<1>', self.cleaned_html)

        self._remove_pre_formatting()

        return self.cleaned_html
245536
def record_remove_tags(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/removeTags' % object_id, input_params, always_retry=always_retry, **kwargs)
754075
function stripBlock( element, enterTag, toBeChecked ) {
		var children = element.children;

		// First, check if element's children may be wrapped with <p/div>.
		// Ignore that <p/div> may not be allowed in element.parent.
		// This will be fixed when removing parent or by toBeChecked rule.
		if ( checkChildren( children, enterTag ) ) {
			element.name = enterTag;
			element.attributes = {};
			// Check if this p/div was put in correct context.
			// If not - strip parent.
			toBeChecked.push( { check: 'parent-down', el: element } );
			return;
		}

		var parent = element.parent,
			shouldAutoP = parent.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT || parent.name == 'body',
			i, child, p;

		for ( i = children.length; i > 0; ) {
			child = children[ --i ];

			// If parent requires auto paragraphing and child is inline node,
			// insert this child into newly created paragraph.
			if ( shouldAutoP && inlineNode( child )  ) {
				if ( !p ) {
					p = new CKEDITOR.htmlParser.element( enterTag );
					p.insertAfter( element );

					// Check if this p/div was put in correct context.
					// If not - strip parent.
					toBeChecked.push( { check: 'parent-down', el: p } );
				}
				p.add( child, 0 );
			}
			// Child which doesn't need to be auto paragraphed.
			else {
				p = null;
				child.insertAfter( element );
				// If inserted into invalid context, mark it and check
				// after removing all elements.
				if ( parent.type != CKEDITOR.NODE_DOCUMENT_FRAGMENT &&
					child.type == CKEDITOR.NODE_ELEMENT &&
					!DTD[ parent.name ][ child.name ]
				)
					toBeChecked.push( { check: 'el-up', el: child } );
			}
		}

		// All children have been moved to element's parent, so remove it.
		element.remove();
	}
1125541
function finish_html() {
        global $OUTPUT;
        if (!$this->started_output) {
            //no data has been added to the table.
            $this->print_nothing_to_display();

        } else {
            // Print empty rows to fill the table to the current pagesize.
            // This is done so the header aria-controls attributes do not point to
            // non existant elements.
            $emptyrow = array_fill(0, count($this->columns), '');
            while ($this->currentrow < $this->pagesize) {
                $this->print_row($emptyrow, 'emptyrow');
            }

            echo html_writer::end_tag('tbody');
            echo html_writer::end_tag('table');
            echo html_writer::end_tag('div');
            $this->wrap_html_finish();

            // Paging bar
            if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
                echo $this->download_buttons();
            }

            if($this->use_pages) {
                $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
                $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
                echo $OUTPUT->render($pagingbar);
            }
        }
    }
1058296
def make_tag(name, attrs, start_end=False):
    

    text = '<' + name

    if isinstance(attrs, dict):
        attr_list = attrs.items()
    elif isinstance(attrs, list):
        attr_list = attrs
    elif attrs is not None:
        raise TypeError("Unhandled attrs type " + str(type(attrs)))

    for key, val in attr_list:
        if val is not None:
            escaped = html.escape(str(val), False).replace('"', '&#34;')
            text += ' {}="{}"'.format(key, escaped)
    if start_end:
        text += ' /'
    text += '>'
    return flask.Markup(text)
608653
def strip_html(html)
      return @stripped_html if @stripped_html
      allowed = @settings[:allowed_tags]
      reg = if allowed.any?
        Regexp.new(
          %(<(?!(\\s|\\/)*(#{
            allowed.map {|tag| Regexp.escape( tag )}.join( "|" )
          })( |>|\\/|'|"|<|\\s*\\z))[^>]*(>+|\\s*\\z)),
          Regexp::IGNORECASE | Regexp::MULTILINE, 'u'
        )
      else
        /<[^>]*(>+|\s*\z)/m
      end
       @stripped_html = html.gsub(reg,'')
    end
706489
function detach() {
                if (!this._placeholder) {
                    this._placeholder = document.createElement(this.el.tagName);
                }
                if (!this._parent) {
                    this._parent = this.el.parentNode;
                }

                if (this.el && this._parent) {
                    this._parent.replaceChild(this._placeholder, this.el);
                }
            }
1341161
def _clean_html(html):
    
    content = html.replace(u'&#x000A;', u'\n').replace(u'¶', '')
    content = _LINK_PATTERN.sub(u'', content)
    content = _HTML_TAG_PATTERN.sub(u'', content)
    content = _BACKSLASH_PATTERN.sub(u'\n', content)
    return content
1169999
public void endDocument() throws IOException {
		// close all unclosed tag;
		while (depth > 0) {
			endTag(elNamespace[depth], elName[depth]);
		}
		// assert depth == 0;
		// assert startTagIncomplete == false;
		finished = pastRoot = startTagIncomplete = true;
		out.flush();
	}