简体   繁体   中英

How to change css via Jquery on dynamically created element before adding to document DOM

I have this dynamically created Element, created via 3rd party lib (jsondiffpatch.formatters.html.format()).

I want to do some css and content changes on it before adding to document DOM.

I tried doing this but failed:

function transformDelta(deltaHtml: any) {
  $(deltaHtml)
    .find(".jsondiffpatch-delta > ul > li")
    .each(function () {
      console.log($(this).text());
    });
  return deltaHtml;
}

How is this done?

Additional codes:

Button to display the json changes

<ChangesModalButton
  variant="primary"
  getMatrixDelta={() => {
    const delta = diffpatcher.diff(orig, cur);
    const deltaHtml = jsondiffpatch.formatters.html.format(delta);
    const Container = (
        <div dangerouslySetInnerHTML={{ __html: deltaHtml }} />
      );
    return Container;
  }}
/>

The Button definition that displays the modal

export function ChangesModalButton(props: any) {
  const [modalShow, setModalShow] = React.useState(false);
  const [matrixDelta, setMatrixDelta] = React.useState<any>(null);

  return (
    <React.Fragment>
      <ChangesModal
        matrixDelta={matrixDelta}
      />

      <Button
        onClick={() => {
          setMatrixDelta(props.getMatrixDelta());
          setModalShow(true);
        }}
      >
        <img src={seeChangesMatrixImg} alt="" />
      </Button>
    </React.Fragment>
  );
}

Modal definition

class ChangesModal extends Component<any> {
  render() {
    return (
      <Modal
      >
        <Modal.Body>{this.props.matrixDelta? this.props.matrixDelta: "No Changes"}</Modal.Body>           
      </Modal>
    );
  }
}

First thing is that you can't do css changes until dom is rendered. After Dom is rendered you can do css changes.

If you are going to change an elemenet color in css let say element is p1 then

 $(p1).css('color','blue');
 $('#myId').css('color','blue');//to target id let say Id : myId
 $('.myClass').css('color','blue');//to target class let say css: myClass

Or to change its content

 $(p1).html("this is new text added dynamically with JQuery");
 $('#myId').html("this is new text added dynamically with JQuery");//to target id let say Id : myId
 $('.myClass').html("this is new text added dynamically with JQuery");//to target class let say css: myClass

just use the css method https://api.jquery.com/css/ as follows

function transformDelta(deltaHtml: any) {
  $(deltaHtml)
    .find(".jsondiffpatch-delta > ul > li")
    .each(function () {
      $(this).css({"color": "red"})
      console.log($(this).text());
    });
  return deltaHtml;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM