简体   繁体   中英

How to replace whole HTMLElement's text to something else?

Here's the example.

webBrowser1.Document.Body.InnerHtml contains:

<img id="image1" src="myImage.gif">

and in my MyWebBrowser class I want to replate whole img tag to some text, for example to string: "&ltmyImage&gt" (I need it for my chat application, if user doesn't want to see images)

I thought I could do something like that:

Document.GetElementById("image1").InnerHtml = "&lt" + Document.GetElementById("image1").GetAttribute("src") + "&gt";

but it throws exception.

Actually I resolved that by searching those specific tags in whole document and replacing it using String class' methods, but code doesn't look good. If there's more effective way to do that, do not bother answering my question.

You can use the OuterHtml property:

HtmlElement image = Document.GetElementById("image1");
image.OuterHtml = "&lt;" + image.GetAttribute("src") + "&gt;";

Note, however, that assigning to OuterHtml will invalidate the reference to the element, so image will not refer to the new content afterwards.

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