Append html with css

Using CSS generated content

This article describes some ways in which you can use CSS to add content when a document is displayed. You modify your stylesheet to add text content or images.

One of the important advantages of CSS is that it helps you to separate a document’s style from its content. However, there are situations where it makes sense to specify certain content as part of the stylesheet, not as part of the document. You can specify text or image content within a stylesheet when that content is closely linked to the document’s structure.

Note: Content specified in a stylesheet does not become part of the DOM.

Specifying content in a stylesheet can cause complications. For example, you might have different language versions of your document that share a stylesheet. If you specify content in your stylesheet that requires translation, you have to put those parts of your stylesheet in different files and arrange for them to be linked with the appropriate language versions of your document.

Читайте также:  Registration

This issue does not arise if the content you specify consists of symbols or images that apply in all languages and cultures.

Examples

Text content

CSS can insert text content before or after an element, or change the content of a list item marker (such as a bullet symbol or number) before a or other element with display: list-item; . To specify this, make a rule and add ::before , ::after , or ::marker to the selector. In the declaration, specify the content property with the text content as its value.

HTML

span class="ref">somethingspan> 

CSS

.ref::before  font-weight: bold; color: navy; content: "Reference "; > 

Output

The character set of a stylesheet is UTF-8 by default, but it can also be specified in the link, in the stylesheet itself, or in other ways. For details, see 4.4 CSS style sheet representation in the CSS Specification.

Individual characters can also be specified by an escape mechanism that uses backslash as the escape character. For example, «\265B» is the chess symbol for a black queen ♛. For details, see Referring to characters not represented in a character encoding and Characters and case in the CSS Specification.

Image content

To add an image before or after an element, you can specify the URL of an image file in the value of the content property.

This rule adds a space and an icon after every link that has the class glossary :

HTML

a href="developer.mozilla.org" class="glossary">developer.mozilla.orga> 

CSS

a.glossary::after  content: " " url("glossary-icon.gif"); > 

Found a content problem with this page?

This page was last modified on Jun 30, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Element: innerHTML property

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.

To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

Value

A string containing the HTML serialization of the element’s descendants. Setting the value of innerHTML removes all of the element’s descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

Exceptions

Thrown if an attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.

Thrown if an attempt was made to insert the HTML into a node whose parent is a Document .

Usage notes

The innerHTML property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.

Reading the HTML contents of an element

Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element’s descendants. The resulting string is returned.

let contents = myElement.innerHTML; 

This lets you look at the HTML markup of the element’s content nodes.

Note: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.

Replacing the contents of an element

Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.

Note: This is a security risk if the string to be inserted might contain potentially malicious content. When inserting user-supplied data you should always consider using Element.setHTML() instead, in order to sanitize the content before it is inserted.

For example, you can erase the entire contents of a document by clearing the contents of the document’s body attribute:

This example fetches the document’s current HTML markup and replaces the »

.documentElement.innerHTML = ` $document.documentElement.innerHTML.replace( //g, "<", )> `; 

Operational details

What exactly happens when you set value of innerHTML ? Doing so causes the user agent to follow these steps:

  1. The specified value is parsed as HTML or XML (based on the document type), resulting in a DocumentFragment object representing the new set of DOM nodes for the new elements.
  2. If the element whose contents are being replaced is a element, then the element’s content attribute is replaced with the new DocumentFragment created in step 1.
  3. For all other elements, the element’s contents are replaced with the nodes in the new DocumentFragment .

Appending HTML to an element

Setting the value of innerHTML lets you append new contents to the existing one of an element.

HTML

ul id="list"> li>a href="#">Item 1a>li> li>a href="#">Item 2a>li> li>a href="#">Item 3a>li> ul> 

JavaScript

Please note that using innerHTML to append HTML elements (e.g. el.innerHTML += «link» ) will result in the removal of any previously set event listeners. That is, after you append any HTML element that way you won’t be able to listen to the previously set event listeners.

Security considerations

It is not uncommon to see innerHTML used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.

let name = "John"; // assuming 'el' is an HTML DOM element el.innerHTML = name; // harmless in this case // … name = ""; el.innerHTML = name; // harmless in this case 

Although this may look like a cross-site scripting attack, the result is harmless. HTML specifies that a tag inserted with innerHTML should not execute.

const name = ""; el.innerHTML = name; // shows the alert 

For that reason, it is recommended that instead of innerHTML you use:

  • Element.setHTML() to sanitize the text before it is inserted into the DOM.
  • Node.textContent when inserting plain text, as this inserts it as raw text rather than parsing it as HTML.

Warning: If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it may be rejected in the review process. Please see Safely inserting external content into a page for alternative methods.

Examples

This example uses innerHTML to create a mechanism for logging messages into a box on a web page.

JavaScript

function log(msg)  const logElem = document.querySelector(".log"); const time = new Date(); const timeStr = time.toLocaleTimeString(); logElem.innerHTML += `$timeStr>: $msg>
`
; > log("Logging mouse events inside this container…");

The log() function creates the log output by getting the current time from a Date object using toLocaleTimeString() , and building a string with the timestamp and the message text. Then the message is appended to the box with the class «log» .

We add a second method that logs information about MouseEvent based events (such as mousedown , click , and mouseenter ):

function logEvent(event)  const msg = `Event $event.type> at $event.clientX>, $event.clientY> `; log(msg); > 

Then we use this as the event handler for a number of mouse events on the box that contains our log:

const boxElem = document.querySelector(".box"); boxElem.addEventListener("mousedown", logEvent); boxElem.addEventListener("mouseup", logEvent); boxElem.addEventListener("click", logEvent); boxElem.addEventListener("mouseenter", logEvent); boxElem.addEventListener("mouseleave", logEvent); 

HTML

The HTML is quite simple for our example.

div class="box"> div>strong>Log:strong>div> div class="log">div> div> 

CSS

The following CSS styles our example content.

.box  width: 600px; height: 300px; border: 1px solid black; padding: 2px 4px; overflow-y: scroll; overflow-x: auto; > .log  margin-top: 8px; font-family: monospace; > 

Result

The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Node.textContent and HTMLElement.innerText
  • Element.insertAdjacentHTML()
  • Element.outerHTML
  • Element.setHTML
  • Parsing HTML or XML into a DOM tree: DOMParser
  • Serializing a DOM tree into an XML string: XMLSerializer

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How To Add CSS

When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.

Three Ways to Insert CSS

There are three ways of inserting a style sheet:

External CSS

With an external style sheet, you can change the look of an entire website by changing just one file!

Each HTML page must include a reference to the external style sheet file inside the element, inside the head section.

Example

External styles are defined within the element, inside the section of an HTML page:

This is a heading

This is a paragraph.

An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Here is how the «mystyle.css» file looks:

«mystyle.css»

body <
background-color: lightblue;
>

h1 color: navy;
margin-left: 20px;
>

Note: Do not add a space between the property value (20) and the unit (px):
Incorrect (space): margin-left: 20 px;
Correct (no space): margin-left: 20px;

Internal CSS

An internal style sheet may be used if one single HTML page has a unique style.

The internal style is defined inside the element, inside the head section.

Example

Internal styles are defined within the element, inside the section of an HTML page:

This is a heading

This is a paragraph.

Inline CSS

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.

Example

Inline styles are defined within the «style» attribute of the relevant element:

This is a heading

This is a paragraph.

Tip: An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly.

Multiple Style Sheets

If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used.

Assume that an external style sheet has the following style for the element:

Then, assume that an internal style sheet also has the following style for the element:

Example

If the internal style is defined after the link to the external style sheet, the elements will be «orange»:

Example

However, if the internal style is defined before the link to the external style sheet, the elements will be «navy»:

Cascading Order

What style will be used when there is more than one style specified for an HTML element?

All the styles in a page will «cascade» into a new «virtual» style sheet by the following rules, where number one has the highest priority:

  1. Inline style (inside an HTML element)
  2. External and internal style sheets (in the head section)
  3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and browser defaults.

Ever heard about W3Schools Spaces? Here you can create your own website, or save code snippets for later use, for free.

Источник

Оцените статью