developer tip

DOM에 HTML 문자열 추가

optionbox 2020. 8. 20. 08:12
반응형

DOM에 HTML 문자열 추가


이 HTML 문자열을 추가하는 방법

var str = '<p>Just some <span>text</span> here</p>';

'test'DOM에있는 ID로 DIV에 ?

(Btw div.innerHTML += str;는 허용되지 않습니다.)


사용 insertAdjacentHTML이 가능한 경우는 true, 그렇지 않은 경우는 대체 어떤 종류를 사용합니다. insertAdjacentHTML 은 현재의 모든 브라우저에서 지원됩니다 .

div.insertAdjacentHTML( 'beforeend', str );

라이브 데모 : http://jsfiddle.net/euQ5n/


이것이 허용됩니까?

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle .

그러나 , 닐의 대답은 더 나은 솔루션입니다.


아이디어는 innerHTML중간 요소에서 사용한 다음 모든 자식 노드를를 통해 실제로 원하는 위치로 이동하는 것 appendChild입니다.

var target = document.getElementById('test');
var str = '<p>Just some <span>text</span> here</p>';

var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
  target.appendChild(temp.firstChild);
}

이것은 이벤트 핸들러를 지우는 것을 방지 div#test하지만 여전히 HTML 문자열을 추가 할 수 있습니다.


다음은 몇 가지 성능 테스트입니다.

환경 설정 (2019.07.10) Chrome 75.0.3770 (64 비트), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64 비트)에서 MacOs High Sierra 10.13.4

여기에 이미지 설명 입력

  • Chrome E (초당 140k 작업)가 가장 빠르고 B (47k) 및 F (46k)가 초, A (332)가 가장 느립니다.
  • 파이어 폭스에서 F (94k)가 가장 빠르며 B (80k), D (73k), E (64k), C (21k) 가장 느림은 A (466)입니다.
  • Safari E (207k)에서 가장 빠르며 B (89k), F (88k), D (83k), C (25k), 가장 느린 것은 A (509)입니다.

요약

AppendChild(E)는 크롬 및 사파리의 다른 솔루션보다 2 배 이상 빠르며, insertAdjacentHTML(F)는 파이어 폭스에서 가장 빠릅니다. innerHTML=(B) (와 혼동하지 마십시오는 +=) 모든 브라우저에서 두 번째 빠른 솔루션이며 컴퓨터에서 테스트를 재생할 수 있습니다 훨씬 더 편리한 E와 F 당신보다 여기

function A() {    
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';
}

function B() {    
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';
}

function C() {    
  $('#container').append('<p>C: Just some <span>text</span> here</p>');
}

function D() {
  var p = document.createElement("p");
  p.innerHTML = 'D: Just some <span>text</span> here';
  container.appendChild(p);
}

function E() {    
  var p = document.createElement("p");
  var s = document.createElement("span"); 
  s.appendChild( document.createTextNode("text ") );
  p.appendChild( document.createTextNode("E: Just some ") );
  p.appendChild( s );
  p.appendChild( document.createTextNode(" here") );
  container.appendChild(p);
}

function F() {    
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');
}

A();
B();
C();
D();
E();
F();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This snippet only for show code used in test (in jsperf.com) - it not perform test itself. 
<div id="container"></div>


The right way is using insertAdjacentHTML. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment if your str contains no script tags.

If your str contains script tags, you need to remove script elements from the fragment returned by createContextualFragment before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML marks scripts unexecutable.)


Why is that not acceptable?

document.getElementById('test').innerHTML += str

would be the textbook way of doing it.


Quick Hack:


<script>
document.children[0].innerHTML="<h1>QUICK_HACK</h1>";
</script>

Use Cases:

1: Save as .html file and run in chrome or firefox or edge. (IE wont work)

2: Use in http://js.do

In Action: http://js.do/HeavyMetalCookies/quick_hack

Broken down with comments:

<script>

//: The message "QUICK_HACK" 
//: wrapped in a header #1 tag.
var text = "<h1>QUICK_HACK</h1>";

//: It's a quick hack, so I don't
//: care where it goes on the document,
//: just as long as I can see it.
//: Since I am doing this quick hack in
//: an empty file or scratchpad, 
//: it should be visible.
var child = document.children[0];

//: Set the html content of your child
//: to the message you want to see on screen.
child.innerHTML = text;

</script>

Reason Why I posted:

JS.do has two must haves:

  1. No autocomplete
  2. Vertical monitor friendly

그러나 console.log 메시지는 표시되지 않습니다. 빠른 해결책을 찾기 위해 여기에 왔습니다. 스크래치 패드 코드 몇 줄의 결과를보고 싶을 뿐이고 다른 솔루션은 작업이 너무 많습니다.


이것은 해결할 수 있습니다

 document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');

InnerHTML은 기존 노드에 대한 이벤트와 같은 모든 데이터를 지 웁니다.

firstChild와 함께 자식 추가는 innerHTML에 첫 번째 자식 만 추가합니다. 예를 들어 다음을 추가해야하는 경우 :

 <p>text1</p><p>text2</p>

text1 만 표시됩니다.

이것에 대해 :

자식을 추가하여 innerHTML에 특수 태그를 추가 한 다음 생성 한 태그를 삭제하여 outerHTML을 편집합니다. 얼마나 똑똑한 지 모르겠지만 나를 위해 작동하거나 outerHTML을 innerHTML로 변경하여 함수 교체를 사용할 필요가 없습니다.

function append(element, str)
{

  var child = document.createElement('someshittyuniquetag');
		
  child.innerHTML = str;

  element.appendChild(child);

  child.outerHTML = child.outerHTML.replace(/<\/?someshittyuniquetag>/, '');

// or Even child.outerHTML = child.innerHTML


  
}
<div id="testit">
This text is inside the div
<button onclick="append(document.getElementById('testit'), '<button>dadasasdas</button>')">To div</button>
<button onclick="append(this, 'some text')">to this</button>
</div>

참고 URL : https://stackoverflow.com/questions/7327056/appending-html-string-to-the-dom

반응형