Dynamically add class to img tag from entire HTML

asp.net c# html-agility-pack

Question

I have an rich editor which adds text and images,to make the images responsive

class="img-thumbnail"

is needed in all the image tags,so have used HtmlAgility pack to extract image tags from entire Html but how to add the class on each image tag.

Example

Input from html after extracting image tag

<img src="http://domain.com/images/image1.jpg">

Expected

<img src="http://domain.com/images/image1.jpg" class="img-thumbnail">

Code

 public string ParseImage(string pHtml)
    {

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(pHtml);
        var imgs = doc.DocumentNode.SelectNodes("//img");

        foreach (var item in imgs)
        {
            string orig = item.Attributes["src"].Value;
            //Add class to each img tag.
        }
      }

Accepted Answer

I guess the problem lies in that you need to save the HTML before you display it. Otherwise HTML Agility Pack sometimes omits the changed attributes.

public string ParseImage(string pHtml)
{

   HtmlDocument doc = new HtmlDocument();
   doc.LoadHtml(pHtml);
   var imgs = doc.DocumentNode.SelectNodes("//img");

    foreach (var item in imgs)
    {
        //string orig = item.Attributes["src"].Value;
        item.SetAttributeValue("class", "img-thumbnail");
        //Add class to each img tag.
    }
    using(StringWriter tw = new StringWriter ()){
        doc.Save(tw);
        return tw.ToString();
    }
 }

Popular Answer

You can add attributes to all your image tags in css like this

.img-thumbnail
{
  // your class property
}

img {
.img-thumbnail
}

Here is a similar question.

I want to apply an existing CSS style to all labels on a page. How?



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why