Форма

How to get the entire document HTML as a string?

Stop upvoting John’s bolded comment! The answer he links to replaces && with && and so it breaks all your inline tags! You should use document.documentElement.outerHTML instead, but note that it doesn’t grab , so you’ll need to add that yourself.

17 Answers 17

Get the root element with document.documentElement then get its .innerHTML :

const txt = document.documentElement.innerHTML; alert(txt); 

or its .outerHTML to get the tag as well

const txt = document.documentElement.outerHTML; alert(txt); 

worked like a charm! thank you! is there any way to get the size of any/all files linked to the document as well including js and css files?

@CMCDragonkai: You could get the doctype separately and prepend it to the markup string. Not ideal, I know, but possible.

note that neither this nor none of these answers necessarily give you content that is the exact hash equivalent of saving the page to a file or the file generated by view-source. It seems the DOM normalizes some fields from the literal response content, like capitalising DOCTYPE headers

new XMLSerializer().serializeToString(document) 

in browsers newer than IE 9

This was the first correct answer according to date/time stamps. Parts of the page such as the XML declaration will not be included and browsers will manipulate the code when using the other «answers». This is the only post that should be up-voted (dos’s posted three days later). People need to pay attention!

Читайте также:  Render code in html

This is not entirely correct since it serializeToString performs an HTML encode. For example if your code contains styles defining fonts such as «Times New Roman», Times, serif the quotes will get html encoded. Perhaps that is not important to some of you but to me it is.

@John well the OP actually asks for «the entire HTML within the html tags». And the selected best answer by Colin Burnett does achieve this. This particular answer (Erik’s) will include the html tags and the doctype. That said, this was totally a diamond in the rough for me and exactly what I was looking for! Your comment helped too because it made me spend more time with this answer, so thanks 🙂

I think people should be careful with this one, specifically because it returns a value that is not the actual html that your browser receives. In my case, it added attributes to the html tag that the server never actually sent 🙁

I tried the various answers to see what is returned. I’m using the latest version of Chrome.

The suggestion document.documentElement.innerHTML; returned .

Gaby’s suggestion document.getElementsByTagName(‘html’)[0].innerHTML; returned the same.

The suggestion document.documentElement.outerHTML; returned . which is everything apart from the ‘doctype’.

You can retrieve the doctype object with document.doctype; This returns an object, not a string, so if you need to extract the details as strings for all doctypes up to and including HTML5 it is described here: Get DocType of an HTML as string with Javascript

I only wanted HTML5, so the following was enough for me to create the whole document:

alert(» + ‘\n’ + document.documentElement.outerHTML);

This is the most complete answer and should be accepted. As of 2016, browser compatibility is complete, and mentioning it in detail (as in the currently accepted answer) is no longer necessary.

I believe document.documentElement.outerHTML should return that for you.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

The MSDN page on the outerHTML property notes that it is supported in IE 5+. Colin’s answer links to the W3C quirksmode page, which offers a good comparison of cross-browser compatibility (for other DOM features too).

@Colin: Yeah, good point. From experience, I seem to remember that both IE 6+ and Firefox support it, though the quirksmode page you linked suggests otherwise.

document.getElementsByTagName('html')[0].innerHTML 

You will not get the Doctype or html tag, but everything else.

document.documentElement.outerHTML 

Supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile (MDN). outerHTML is in the DOM Parsing and Serialization specification.

//serialize current DOM-Tree incl. changes/edits to ss-variable var ns = new XMLSerializer(); var ss= ns.serializeToString(document); alert(ss.substr(0,300)); 

may work in FF. (Shows up the VERY FIRST 300 characters from the VERY beginning of source-text, mostly doctype-defs.)

BUT be aware, that the normal «Save As»-Dialog of FF MIGHT NOT save the current state of the page, rather the originallly loaded X/h/tml-source-text !! (a POST-up of ss to some temp-file and redirect to that might deliver a saveable source-text WITH the changes/edits prior made to it.)

Although FF surprises by good recovery on «back» and a NICE inclusion of states/values on «Save (as) . » for input-like FIELDS, textarea etc. , not on elements in contenteditable/ designMode.

If NOT a xhtml- resp. xml-file (mime-type, NOT just filename-extension!), one may use document.open/write/close to SET the appr. content to the source-layer, that will be saved on user’s save-dialog from the File/Save menue of FF. see: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite resp.

Neutral to questions of X(ht)ML, try a «view-source:http://. » as the value of the src-attrib of an (script-made!?) iframe, — to access an iframes-document in FF:

.contentDocument , see google «mdn contentDocument» for appr. members, like ‘textContent’ for instance. ‘Got that years ago and no like to crawl for it. If still of urgent need, mention this, that I got to dive in .

Источник

Как вывести термин и определение в одну строку?

В списке определений термин и его определение вывести на одной строке.

Решение

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

Для выравнивания содержимого тегов используется свойство float со значением left , добавляемое к селектору DT . Добавляя одновременно ширину через width добиваемся того, что элементы выравниваются и по вертикали. В примере 1 создаётся форма, в которой текст и поля располагаются на одной строке. В качестве модульной сетки применяется список определений, при этом текст находится внутри тега , а поле внутри .

Пример 1. Вывод в одну строку

HTML5 CSS 2.1 IE Cr Op Sa Fx

         
Имя
Пароль

Результат данного примера показан на рис. 1. Поля формы немного смещены вниз, поэтому в примере они поднимаются вверх с помощью свойства top с отрицательным значением. Минимальная высота min-height нужна для пустого тега , чтобы он занимал нужный размер.

Использование списка определений для формы

Рис. 1. Использование списка определений для формы

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Популярные рецепты

  • Как добавить картинку на веб-страницу?
  • Как добавить иконку сайта в адресную строку браузера?
  • Как добавить фоновый рисунок на веб-страницу?
  • Как сделать обтекание картинки текстом?
  • Как растянуть фон на всю ширину окна?
  • Как выровнять фотографию по центру веб-страницы?
  • Как разместить элементы списка горизонтально?
  • Как убрать подчеркивание у ссылок?
  • Как убрать маркеры в маркированном списке?
  • Как изменить расстояние между строками текста?
  • Как сделать, чтобы картинка менялась при наведении на нее курсора мыши?
  • Как открыть ссылку в новом окне?

Источник

how convert html tags into string in php

i am trying convert html tag into string in php. but output is does not display actual html tag , output display hello world thanks for watching, i want output as actual html tag , please help me to resolve this problem

 Hello World Thanks for watching!"; echo $tag; ?> 
Hello World Thanks for watching! 
 hello world thanks for watching 

5 Answers 5

Use the following code

Hello World Thanks for watching!"; echo htmlentities($tag); 

use the strip_tags()it delivery actual output what we expected ,string strip_tags ( string $str [, string $allowable_tags ] ) This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

str : The input string.

allowable_tags : You can use the optional second parameter to specify tags which should not be stripped.

$tag=" Hello World Thanks for watching!"; echo strip_tags($tag); echo "\n"; echo strip_tags($tag, ''); 

the output is

Hello World Thanks for watching! 

Источник

How to convert a HTMLElement to a string

I am going to create an XML element in JavaScript to exchange data with server side. I found I can do it with document.createElement . But I do not know how to convert it to string. Is there any API in browser to make it easier? Or is there any JS library including this API? EDIT: I found that browser API XMLSerializer, it should be the right way to serialize to string.

8 Answers 8

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

But it seems I cannot get the inside text with the property outerHTML. I think what I really want is the HTML markup.

You can get the ‘outer-html’ by cloning the element, adding it to an empty,’offstage’ container, and reading the container’s innerHTML.

This example takes an optional second parameter.

Call document.getHTML(element, true) to include the element’s descendents.

document.getHTML= function(who, deep)< if(!who || !who.tagName) return ''; var txt, ax, el= document.createElement("div"); el.appendChild(who.cloneNode(false)); txt= el.innerHTML; if(deep)< ax= txt.indexOf('>')+1; txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax); > el= null; return txt; > 

Suppose your element is entire [object HTMLDocument] . You can convert it to a String this way:

const htmlTemplate = ` `; const domparser = new DOMParser(); const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument] const doctype = ''; const html = doc.documentElement.outerHTML; console.log(doctype + html);

There’s a tagName property, and a attributes property as well:

var element = document.getElementById("wtv"); var openTag = " openTag += ">"; alert(openTag); 

To get the contents between the open and close tags you could probably use innerHTML if you don’t want to iterate over all the child elements.

. and then get the close tag again with tagName .

var closeTag = ""; alert(closeTag); 

If its XML it should all be in one root node, yes? If so, then you only have to do this for the root node — innerHTML is supported on all major browsers, and will give you the X(H)TML nested in the root node. (ie everything!)

Why bother looping over the element’s attributes and building a string ‘tag’ from it? Just wrap the element in ANOTHER element, and take the innerHTML of that new parent element. Voila, instant workaround for outerHTML.

The most easy way to do is copy innerHTML of that element to tmp variable and make it empty, then append new element, and after that copy back tmp variable to it. Here is an example I used to add jquery script to top of head.

var imported = document.createElement('script'); imported.src = 'http://code.jquery.com/jquery-1.7.1.js'; var tmpHead = document.head.innerHTML; document.head.innerHTML = ""; document.head.append(imported); document.head.innerHTML += tmpHead; 

The easiest way that I could find was to use Element.outerHTML.toString()

const element = document.createElement('div'); element.innerHTML="Hello world !"; console.log(element.outerHTML.toString()); 

Источник

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