3

I am stuck trying to remove a style definition from the style attribute of a DIV element. HTML code:

<div class="el1" style="width:800px; max-width:100%" />
...

<div class="el2" style="width:800px; max-width:100%" />

There may be more than 1 of these elements that I need to apply the manipulation to.

Here is what I have thus far using HtmlAgilityPack.

foreach (HtmlNode div in doc.DocumentNode.SelectNodes("//div[@style]"))
{
  if (div != null)
  {
    div.Attributes["style"].Value["max-width"].Remove(); //Remove() does not appear to be a function
  }
 }

My thought process was to select any with a style attribute. Look for a max-width definition and remove it.

Any guidance on how this can be achieved?

1
  • 1
    You can't do it like that. You can only get the style value. From there on you can remove the max-width by using a reg-ex or some other diabolical contraption and finally set it back on the attribute. Commented Aug 10, 2014 at 19:33

1 Answer 1

5

THanks Marcel for pointing me to the right direction:

Here is the solution that worked for me.

HtmlNodeCollection divs = doc.DocumentNode.SelectNodes("//div[@style]");
            if (divs != null)
            {
                foreach (HtmlNode div in divs)
                {
                    string style = div.Attributes["style"].Value;
                    string pattern = @"max-width(.*?)(;)";
                    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                    string newStyle = regex.Replace(style, String.Empty);
                    div.Attributes["style"].Value = newStyle;
                }
            }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your answer it works great! Why don't you mark your own answer as the accepted one?
I used this approach to remove all height styles from td tags but not from tr tags. Worked like a charme!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.