-2

As I mentioned in the title, how can I change the contents of the style attribute within a given HTML tag?

for example:

<table class="MsoTableLightShadingAccent1" border="1" cellspacing="0" cellpadding="0" style="margin-left: 45.9pt; border: none;">

I have got many html code like that. I wrote an RegEx like that in js:

str = str.replace(/(<(?:table)[^<]*)(style="[^"]*")([^>]*>)/gi,'<table style="font-size:medium;">');

this can change table tag but actually i want to delete only "margin-left". How can i do that with js?

Edit: I use summernote. When user paste a text, it triggers onPaste callback and i clean dirty tags and attributes.

  • My tip is to use `document.querySelector()` to find your html tag, and then edit it as an object. – FZs Jan 02 '19 at 11:16

1 Answers1

2

You shouldn't parse HTML with regex, see this famous answer.

JavaScript is perfectly capable of doing what you want though, something like this:

<div id="someID" style="height: 50px; width: 50px; background-color: red; margin-left: 50px;"></div>

<button type="button" onclick="document.getElementById('someID').style.marginLeft = 0;">Click Me!</button>
Matt
  • 3,677
  • 1
  • 14
  • 24
  • I understand it but actually i use summernote and when user paste a text to summernote, i want to clean that. So all pasted text goes to my function. So i dont know any id or class in text, i just clean them. – Mustafa Ulukaya Jan 02 '19 at 11:35
  • Can you get the id of the element (a textarea?) that contains the text? Or use a different CSS selector i.e. `#container > div > div > textarea`? – Matt Jan 02 '19 at 12:21
  • Sorry I think I misunderstood your edit. So the user pastes HTML as text and you receive the HTML in your `onPaste` callback? You could parse that HTML into a DOM object and then find your element and adjust the CSS? See https://stackoverflow.com/questions/10585029/parse-an-html-string-with-js][this answer. – Matt Jan 02 '19 at 12:26
  • Oh, i see. RegEx becomes a little obsession for me so i couldn't see that solution. Thanks a lot. – Mustafa Ulukaya Jan 02 '19 at 12:36