Skip to content

More HtmlElement

Bartosz Kopeć edited this page Jun 13, 2021 · 2 revisions

Class HtmlElement (from namespace HtmlMakerKit.Core.Element) has regex to given markup tag to contructor or static .New method:

^[a-zA-Z0-9]{1,}$

It could throw exception HtmlElementException (from namespace HtmlMakerKit.Core) with given messages:

From contructor:
WRONG_MARKUP = "Format of markup is wrong. Use plain name of markup, in example \"div\" not \"<div>\".";
From adding children:
EMPTY_ELEMENT = "Given html element is null or empty";
From adding attribute:
EMPTY_ATTRIBUTE = "Given html attribute is null or empty";

It has implicit cast to string with using overrided .ToString method:

string html = HtmlElement.New("div");

with result

<div></div>

This example can be more complex:

string html = HtmlElement.New("html").AddChildren(
   HtmlElement.New("head").AddChildren(
      HtmlElement.New("title").SetInnerHTML("My website!"),
         HtmlElement.New("link").AddAttibutes(
            ("rel", "stylesheet"),
	    ("href", "http://example.org/style.css")
	 ),
	 HtmlElement.New("style").SetInnerHTML(
	    "body{color:black;} p{font-size:1.1em;} .title{color:blue;}"
	 )
      ),
      HtmlElement.New("body").AddChildren(
         HtmlElement.New("h1")
	    .AddAttibutes(("class", "title"))
	    .SetInnerHTML("Mega welcome on my website!"),
	 HtmlElement.New("p").SetInnerHTML("Lorem ipsum dotor amar"),
	 HtmlElement.New("script").SetInnerHTML(
            "function job(){console.log(\"bar\");"
	 )
      )
   );

will produce:

<html>
   <head>
      <title>My website!</title>
      <link rel="stylesheet" href="http://example.org/style.css"/>
      <style>
	body{
	   color:black;
	} 
	p{
	   font-size:1.1em;
	} 
	.title{
	   color:blue;
	}			
      </style>
   </head>
   <body>
      <h1 class="title">Mega welcome on my website!</h1>
      <p>Lorem ipsum dotor amar</p>
      <script>
	function job(){console.log("bar");
      </script>
   </body>
</html>
Clone this wiki locally