使用javascript / jquery从字符串元素中删除内联样式

时间:2018-11-27 14:29:29

标签: javascript jquery html regex

假设我有这个字符串:

let string = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>';

所以基本上它是一堆这样的元素,但是在字符串中:

<h1 style="bunch of class"> </h1>
<h2> 
  <p style="bunch of class"> </p>
  <p style="bunch of class"> </p>
</h2>

使用jquery或vanilla javascript,如何从字符串中删除样式属性?

我已经尝试过这个:

$(string).find('h1').removeAttr('style');

但它不起作用

5 个答案:

答案 0 :(得分:3)

这里有两个潜在问题。首先,您需要从string创建一个jQuery对象并保存对其的引用。如果不这样做,将会丢失对HTML所做的更改。

第二,您需要使用filter()而不是find(),因为没有单个根级别 要从HTML字符串中搜索的节点。试试这个:

let string = '<h1 style="color: red;">H1 Foo</h1><h2 style="color: yellow;">H2 Foo<p style="color: green;">P Foo</p><p style="color: blue;">P Foo</p></h2>';

let $string = $(string);
$string.filter('h1').removeAttr('style');
$('body').append($string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 1 :(得分:2)

您可以做的是,在代码中创建一个虚拟元素,然后将内容放入其中。然后找到该元素并删除属性:

b'16296\n'
let str = '<h1 style="lots of class">h1</h1><h2> <p style="bunch of class"> h2 > p</p> <p style="bunch of class"> h2 > p </p></h2>';

let $div = $('<div>')
$div.html(str).find('h1').removeAttr('style');

$(document.body).append($div.html())

答案 2 :(得分:1)

如果您需要从字符串中删除所有样式,则可以这样操作:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { Field, touch, reduxForm, reset } from 'redux-form';
import { Modal } from 'react-bootstrap';
import _ from 'lodash';

import Input from '../../../common/components/Input';
import ReactSelect from '../../../common/components/Input/ReactSelect';
import CenteredModal from '../../../common/components/CenteredModal/index';
import LoadingSpinner from '../../components/LoadingSpinner';
import { selectCurrentUser } from '../../containers/App/selectors';
import { selectSyncErrorBool, selectSyncErrors, selectValues } from '../../common/selectors/form.selector';

import validator, { fields } from './validator';

const formName = 'addCalendarEvent';

function numberSequenceCreator(start, end) {
  return _.range(start, end).map(n => {
    if (n < 10) {
      return {
        label: `0${n}`,
        value: n.toString(),
      };
    }
    return {
      label: n.toString(),
      value: n.toString(),
    };
  });
}

const hourOptions = numberSequenceCreator(1, 13);
const minuteOptions = numberSequenceCreator(0, 60);
const periodOptions = [
  { label: 'AM', value: 'AM' },
  { label: 'PM', value: 'PM' },
];

const mapDispatchToProps = (dispatch) => ({
  touchFields: () => dispatch(touch(formName, ...fields)),
  resetForm: () => dispatch(reset(formName)),
});

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser(),
  formError: selectSyncErrorBool(formName),
  formErrors: selectSyncErrors(formName),
  formValues: selectValues(formName),
});

@reduxForm({
  form: formName,
  validate: validator,
  enableReinitialize: true,
  keepDirtyOnReinitialize: false,
})
@connect(mapStateToProps, mapDispatchToProps)
export default class AddCalendarEventForm extends Component { // eslint-disable-line react/prefer-stateless-function
  static propTypes = {
    resetForm: PropTypes.func,
    currentUser: PropTypes.object,
    formError: PropTypes.bool,
    formErrors: PropTypes.object,
    formValues: PropTypes.object,
    show: PropTypes.bool,
    onHide: PropTypes.func,
    onSubmit: PropTypes.func,
    touchFields: React.PropTypes.func.isRequired,
    calendarEvent: PropTypes.object,
    isSubmitting: PropTypes.bool,
  };

  constructor(props) {
    super(props);

    this.handleCloseModal = this.handleCloseModal.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
  }

  handleCloseModal() {
    this.props.resetForm();
    this.props.onHide(false);
  }

  handleFormSubmit(event) {
    event.preventDefault();
    const { formError, formValues, onSubmit, calendarEvent, touchFields } = this.props;

    if (!formValues.title || !formValues.period || !formValues.hour || !formValues.minute) {
      touchFields();
    } else if (!formError) {
      onSubmit({ event: calendarEvent, formValues });
    }
  }

  render() {
    const { show, isSubmitting } = this.props;

    return (
      <div>
        <Modal
          className="edit-study-modal"
          id="edit-study"
          dialogComponentClass={CenteredModal}
          show={show}
          onHide={this.handleCloseModal}
          backdrop
          keyboard
        >
          <Modal.Header>
            <Modal.Title>Add Calendar Event</Modal.Title>
            <a className="lightbox-close close" onClick={this.handleCloseModal}>
              <i className="icomoon-icon_close" />
            </a>
          </Modal.Header>
          <Modal.Body>
            <div className="form">
              <div className="inner">
                <form className="" onSubmit={this.handleFormSubmit}>
                  <div className="form-lightbox">
                    <div className="clearfix">
                      <div className="field-row">
                        <strong className="required label">
                          <label>Title</label>
                        </strong>
                        <div className="field">
                          <Field
                            name="title"
                            component={Input}
                            type="text"
                          />
                        </div>
                      </div>
                      <div className="field-row time-field-row">
                        <strong className="label required">
                          <label>Time</label>
                        </strong>
                        <div className="field time-field">
                          <div className="row">
                            <div className="col-small pull-left hours">
                              <Field
                                name="hour"
                                placeholder="Hours"
                                options={hourOptions}
                                component={ReactSelect}
                              />
                            </div>
                            <div className="col-small pull-left minutes">
                              <Field
                                name="minute"
                                placeholder="Minutes"
                                options={minuteOptions}
                                component={ReactSelect}
                              />
                            </div>
                            <div className="col-small pull-left time-mode">
                              <Field
                                name="period"
                                placeholder="AM/PM"
                                options={periodOptions}
                                component={ReactSelect}
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="field-row">
                        <strong className="label">
                          <label>Description</label>
                        </strong>
                        <Field
                          name="description"
                          component={Input}
                          className="field"
                          bsClass="form-control input-lg"
                          componentClass="textarea"
                        />
                      </div>
                      <button
                        type="submit"
                        className="btn btn-default btn-submit pull-right"
                      >
                        {isSubmitting
                          ? <span><LoadingSpinner showOnlyIcon size={20} /></span>
                          : <span>Submit</span>
                        }
                      </button>
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </Modal.Body>
        </Modal>
      </div>
    );
  }
}
let string = '<h1 style="color: red;">H1 Foo</h1><h2 style="color: yellow;">H2 Foo<p style="color: green;">P Foo</p><p style="color: blue;">P Foo</p></h2>';

$('<div>' + string + '</div>')
  .find('[style]').attr('style', null)
  .appendTo('body');

更新
为了给您您真正想要的东西,我编写了以下jQuery扩展。
它从html片段中剥离所有属性,但要保留的属性除外。
可以应用于jQuery对象。
保留一个attrs数组(可选)。
像jQuery <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>方法一样返回html字符串。

html()
$.fn.extend({
  stripHTML: function(keep = []) {        
    return $('<div>')
      .append(this)
      .find('*').each(function(i, e) {
        for (var {name} of [...e.attributes]) {
          if (!keep.includes(name)) e.removeAttribute(name);
        }
      })
      .end()
      .html();
  }
});

let string = '<h1 Title="h1" style="color: red;">H1 Foo</h1><h2 style="color: yellow;">H2 Foo<p style="color: green;">P Foo</p><p style="color: blue;" >P <a href="foo">Foo</a></p></h2>';

let keep = ['href', 'name', 'value']; // attrs to keep

let stripped = $(string).stripHTML(keep);

$('body').html(stripped);

console.log(stripped);

答案 3 :(得分:0)

创建一个div并将字符串插入其中的innerHTML。然后选择h1并从其中删除style

var string = '<h1 style="color:red">h1</h1><h2 style="color:red">h2</h2>';
var div = document.createElement("div");
div.innerHTML = string;
div.querySelector("h1").removeAttribute("style");
document.body.append(div) 

答案 4 :(得分:0)

我们可以通过正则表达式来实现。

const string = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>';
const stringNoStyle = string.replace(/style="(.*?)" /g, '')
// <h1> </h1>
// <h2>
//    <p> </p>
//    <p> </p>
// </h2>