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

孤者浪人 提交于 2019-12-11 11:04:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7299969/how-to-replace-whole-htmlelements-text-to-something-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!