Javascript create html tag

Dynamically creating HTML elements using Javascript?

I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don’t want to write the HTML code in the following function to some div, but, I want to return it in a var.

function createMyElements(id1,id2,id3) < //create anchor with id1 //create div with id 2 //create xyz with id3 //now return the html code of above created just now >

html code of elemets in a var and finally i will do document.getElementbyID(«yu»).innerHTML = var_containing_code

6 Answers 6

[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found @ the bottom of the snippet.

// The classic createElement // ------------------------- // create a paragraph element using document.createElement const elem = document.createElement(`p`); elem.id = `myBrandnewDiv1`; // put in some text elem.appendChild(document.createTextNode(`My brand new div #1`)); // append some html (for demo, preferrably don't use innerHTML) elem.innerHTML += ` => created using document.createElement`; // append a new paragraph within #myBrandNewDiv1 const nested = elem.appendChild(document.createElement(`p`)); nested.classList.add(`nested`); // add some text to that nested.textContent = `I am nested!`; // the elements are still in memory, now add the // whole enchillada to the document document.body.appendChild(elem); // insertAdjacentHTML // ------------------ // nest an element within the nested div nested.insertAdjacentHTML(`afterbegin`, ` 
This text will appear above the text of my parent, that being div#nested. Someone had the nerve to insert me using insertAdjacentHTML
`); // Object.assign // ------------- // Use Object.assign to create an element and // assign properties/html to it in one go const newElem = Object.assign( document.createElement(`div`), < id: `myBrandnewDiv2`, innerHTML: `div#myBrandnewDiv2 signing in. I was assigned using Object.assign…`>); document.body.appendChild(newElem); // insertAdjacentElement combined with Object.assign // ------------------------------------------------- // use the above technique combined with insertAdjacentElement newElem.insertAdjacentElement( `beforeend`, Object.assign(document.createElement(`span`), < id: `myBrandnewnested2_nested`, innerHTML: `
Me too! And appended I was with insertAdjacentElement` >) ); // createDocumentFragment // ---------------------- // Use a document fragment to create/inject html const fragment = document.createDocumentFragment(); const mdnLnk = `https://developer.mozilla.org/en-US/` + `docs/Web/API/Document/createDocumentFragment`; fragment.appendChild( Object.assign( document.createElement(`p`), createDocumentFragment
(see ">MDN)`>) ); document.querySelector(`#myBrandnewDiv2`).appendChild(fragment); // Create, but don't inject // ------------------------ const virtual = Object.assign( document.createElement(`p`), < innerHTML: ` id1
Hi!

Hi 2!

`, classList: [`xyz`], > ); const prepareHtml4Reporting = html => html.replace(/html only
$ `);

I have used some of these methods in this library (see /src/DOM.js ), with a mechanism for sanitizing html before it is injecting.

Источник

document.createElement

В HTML-документах создаёт элемент c тем тегом, что указан в аргументе или HTMLUnknownElement , если имя тега не распознаётся.

В XUL-документах создаёт указанный в аргументе элемент XUL.

В остальных случаях создаёт элемент с нулевым NamespaceURI.

Параметры

var element = document.createElement(tagName, [options]);
  • element — созданный объект элемента.
  • tagName — строка, указывающая элемент какого типа должен быть создан. nodeName создаётся и инициализируется со значением tagName .
  • options — необязательный параметр, объект ElementCreationOptions , который может содержать только поле is , указывающее имя пользовательского элемента, созданного с помощью customElements.define() (см. Веб-компоненты).

Пример

Данный пример создаёт новый элемент и вставляет его перед элементом с идентификатором org_div1 :

div>h1>Привет!h1>div> div id='org_div1'>Текст выше сгенерирован автоматически.div> 
.body.onload = addElement; var my_div = newDiv = null; function addElement()  // Создаём новый элемент div // и добавляем в него немного контента var newDiv = document.createElement("div"); newDiv.innerHTML = "

Привет!

"
; // Добавляем только что созданный элемент в дерево DOM my_div = document.getElementById("org_div1"); document.body.insertBefore(newDiv, my_div); >

Примечания

Если существуют атрибуты со значениями по умолчанию, атрибуты узлов предоставляющие их создаются автоматически и применяются к элементу.

Для создания элементов с заданным пространством имён используйте метод createElementNS.

Реализация createElement в Gecko не соответствует DOM спецификации для XUL и XHTML документов: localName и namespaceURI не устанавливаются в null в созданном документе. Смотрите баг 280692 для подробностей.

Для обратной совместимости с предыдущими версиями спецификации пользовательских элементов некоторые браузеры позволяют передавать здесь строку вместо объекта, где значением строки является имя тега пользовательского элемента.

Спецификации

Found a content problem with this page?

Источник

Три способа создать HTML элемент в JavaScript

Здравствуйте! В сегодняшней статье мы рассмотрим три способа модификации страницы сайта, при помощи JavaScript. Итак. Нам нужно будет создать рабочую папку с html и js файлами.

Первый способ, предполагает использование метода createElement().

В js файле прописываем код:

Создадим HTML-элемент div в JavaScript, вызвав метод createElement() для объекта документа .
Этот метод принимает аргумент, который будет элементом HTML.
Затем, назначим его константе с именем container.
Установим для свойства id ящика значение ' container '.
И добавим его в иерархию DOM методом appendChild()

const container = document.createElement("div");
container.id = "container";
document.body.appendChild(container);

Теперь к элементу container можно добавить дочерний элемент кнопки.

const btn = document.createElement('btn');
btn.innerText = 'btn';
btn.id = 'btn-1';
container.appendChild(btn);

Второй способ - использование Object.Assign().

Метод копирует в первый аргумент значения из последующих.

Третий способ - Обратные кавычки.

Данный способ является самым простым из всех используемых. Мы просто создаем строку с html внутри js файла и присваиваем ее константе. Далее добавляем строку в структуру DOM, назначив ее свойству innerHTML документа document.body.

Таким образом, мы рассмотрели несколько вариантов модификации HTML при помощи JavaScript.

Создано 01.12.2022 12:10:46

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Create HTML tag from Javascript object

    Easy but complicated? Does not sound right. If you don't like using methods why not just concatenate a string then and insert it via the .html() method?

    I meant what the method does is complicated - it wraps the img tag in a div to get the html code of that div. And the element is really created, it tries to load the img.jpg in my browser even if I don't attach it to the DOM.

    6 Answers 6

    You do not need to wrap it in a div using multiple functions and get the html, just use get(0) to get the DOM element and outerHTML to get the element's html representation.

    Unless you are using browsers really old you can rely on outerHTML

    Here is a JSPerf to compare the performance diff between the approaches.

    @PSL: Yes, thank you very much! I just wait if someone comes up with a simple "implode" function which is not creating an element internally before I accept your answer. I thought about the outerHTML solution before I posted the question here but discarded it because of compatibility without checking it.

    Perhaps slightly more concise than PSL's?

    Well no difference though. jquery internally uses array itself. jsperf.com/get-vs-array. But i would've used [0] as well, but didn't want to edit.. 🙂 +1 though.

    The return value of $('',object); is a jQuery object but I need a string containing the HTML code. This is for a template system and I can use jQuery to generate the string but cannot use the object.

    $('', obj)[0] or $('', obj).get(0) ?!

    If you are only doing one element, then this solution is overkill, but I thought I would post it anyway as I don't know what your project is.

    Have you considered a JavaScript template engine? I've been playing around with Swig lately, as it is quite lightweight, but there are many options. Basically, you create a template, pass a JavaScript object, and the compiled template is executed, returning a string of HTML.

    Example from Swig Documentation

    Template

    JavaScript to Render Template

    var template = require('swig'); var tmpl = template.compileFile('/path/to/template.html'); tmpl.render(< // The return value of this function is your output HTML pagename: 'awesome people', authors: ['Paul', 'Jim', 'Jane'] >); 

    Источник

    Читайте также:  Поворот матрицы numpy python
    Оцените статью