itsource

innerText와 inner의 차이HTML과 가치?

mycopycode 2022. 9. 21. 00:02
반응형

innerText와 inner의 차이HTML과 가치?

innerHTML,innerText ★★★★★★★★★★★★★★★★★」valueJavaScript?

다음의 예는, 다음의 HTML 스니펫을 참조하고 있습니다.

<div id="test">
   Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>

노드는 다음 JavaScript에서 참조됩니다.

var x = document.getElementById('test');


element.innerHTML

요소의 하위 항목을 설명하는 HTML 구문을 설정하거나 가져옵니다.

x.innerHTML
// => "
// =>   Warning: This element contains <code>code</code> and <strong>strong language</strong>.
// => "

이것은 W3C의 DOM 해석시리얼화 사양의 일부입니다.주의해 주세요.Element★★★★★★★★★★★★★★★★★★.


node.innerText

개체의 시작 태그와 끝 태그 사이의 텍스트를 설정하거나 가져옵니다.

x.innerText
// => "Warning: This element contains code and strong language."
  • innerTextFirefox에 의해 되지 않았습니다. 8일innerText는 WHATWG에 의해 채택되어 v45에서 Firefox에 추가되었습니다.
  • innerText는 브라우저에 의해 렌더링된 내용과 일치하도록 시도하는 스타일 인식 텍스트를 나타냅니다.것음
    • innerTexttext-transform ★★★★★★★★★★★★★★★★★」white-space이 정해져 있습니다.
    • innerText는 행간의 줄합니다.
    • innerText는, 보이지 않는 .
  • innerTexttextContent「이러한 요소」와 같이 않는 .<style />' ''
  • Node


node.textContent

노드 및 하위 노드의 텍스트 내용을 가져오거나 설정합니다.

x.textContent
// => "
// =>   Warning: This element contains code and strong language.
// => "

이것은 W3C 규격이지만 IE <9에서는 지원되지 않습니다.

  • 스타일링을 모르기 때문에 CSS에 의해 숨겨진 콘텐츠를 반환한다.
  • 리플로우를 트리거하지 않음(따라서 성능이 향상됨)
  • Node


node.value

이건 당신이 목표로 삼은 요소에 따라 달라져요.에서는 " " " 입니다.x에는 htMLDivElement 객체가 포함되어 있지 않습니다.value속성이 정의되어 있습니다.

x.value // => null

태그 「 」 )<input />), 예를 들어 "컨트롤의 현재 값"을 나타내는 속성을 정의합니다.

<input id="example-input" type="text" value="default" />
<script>
  document.getElementById('example-input').value //=> "default"
  // User changes input to "something"
  document.getElementById('example-input').value //=> "something"
</script>

문서에서:

주의: 일부 입력 유형에서는 반환된 값이 사용자가 입력한 값과 일치하지 않을 수 있습니다.가 숫자 의 값을 <input type="number">반환되는 값은 빈 문자열일 수 있습니다.


샘플 스크립트

위의 HTML 출력 예를 다음에 나타냅니다.

var properties = ['innerHTML', 'innerText', 'textContent', 'value'];

// Writes to textarea#output and console
function log(obj) {
  console.log(obj);
  var currValue = document.getElementById('output').value;
  document.getElementById('output').value = (currValue ? currValue + '\n' : '') + obj; 
}

// Logs property as [propName]value[/propertyName]
function logProperty(obj, property) {
  var value = obj[property];
  log('[' + property + ']'  +  value + '[/' + property + ']');
}

// Main
log('=============== ' + properties.join(' ') + ' ===============');
for (var i = 0; i < properties.length; i++) {
  logProperty(document.getElementById('test'), properties[i]);
}
<div id="test">
  Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>
<textarea id="output" rows="12" cols="80" style="font-family: monospace;"></textarea>

★★★★★★★★★★★★★★★와 달리innerText ,,,,innerHTMLHTML 리치 텍스트로 작업할 수 있으며 텍스트를 자동으로 인코딩 및 디코딩하지 않습니다. 말하면, 「 」입니다.innerText합니다.단, 태그의 내용을 플레인텍스트로 합니다.innerHTMLhtml HTML 형형형츠를하취득 。

InnerText- 을 인코딩하여 property html - 내 property - - -html을 변환합니다.<p>로로 합니다.&lt;p&gt;하려면 , 「HTML」을 사용합니다.InnerHTML.

간단히 말하면:

  1. innerText 값도 됩니다.HTML포함시킬 수 있는 포맷.
  2. innerHTML합니다.HTML맷합니니다다

다.innerText ★★★★★★★★★★★★★★★★★」innerHTML HTML 요소의 내부 부분을 반환합니다.

와의 유일한 차이점은 다음과 같습니다.innerText 요소 코드 코드합니다.한편 HTML 요소(HTML 코드)는 코드(HTML 코드)로 표시합니다.innerHTMLHTML html html html html html html html 。

아래 예에서 더 자세히 알아보십시오.다음 코드를 실행합니다.

const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';
document.getElementById('innertext').innerText = ourstring;
document.getElementById('innerhtml').innerHTML = ourstring;
.name {
    color:red;
}
<p><b>Inner text below. It inject string as it is into the element.</b></p>
<p id="innertext"></p>
<br>
<p><b>Inner html below. It renders the string into the element and treat as part of html document.</b></p>
<p id="innerhtml"></p>

var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);

예를 들어 Alex 값을 가져오려면 다른 .childNodes [ 1 ]를 사용합니다.

var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);

MutationObservers, " "innerHTML는 을 합니다.childList한 후 새됩니다.innerHTML

「 」를 설정했을 innerText ,a ,acharacterData변환이 생성됩니다.

innerText및그 노드의 property는 "Node"와 "Node"의 모든 하위 텍스트로 설정합니다.innerHTML속성은 요소의 일반 텍스트 또는 HTML 내용을 가져오고 설정합니다.★★★★★★★★★★★★★★★와 달리innerText,innerHTMLHTML 리치 텍스트로 작업할 수 있으며 텍스트를 자동으로 인코딩 및 디코딩하지 않습니다.

InnerText는, 각 , 「 」는, 「 」의 「 」의 「 」의 「 」는, 「 」의 「 」의 「 」로 표시됩니다.innerHTML는, HTML 에 모든 의 HTML .body 및 "tag", "tagchildNodes이름에서 알 수 있듯이 노드 목록이 반환됩니다.

innerTextproperty는 html 요소의 실제 텍스트 값을 반환합니다.innerHTMLHTML content 음음:

var element = document.getElementById('hello');
element.innerText = '<strong> hello world </strong>';
console.log('The innerText property will not parse the html tags as html tags but as normal text:\n' + element.innerText);

console.log('The innerHTML element property will encode the html tags found inside the text of the element:\n' + element.innerHTML);
element.innerHTML = '<strong> hello world </strong>';
console.log('The <strong> tag we put above has been parsed using the innerHTML property so the .innerText will not show them \n ' + element.innerText);
console.log(element.innerHTML);
<p id="hello"> Hello world 
</p>

하려면 , 「」를 참조해 주세요.innerText text-transform,innerHTML

innerhtml은 html 코드를 적용합니다.

innertext는 내용을 텍스트로 표시하므로 html 태그가 있는 경우 텍스트로만 표시됩니다.

@rule:

innerHTML

  • 쓰기에 : " " " "ele.innerHTML,ele(html 파에에에) String 。

  • : read 에서 을 읽었든 : 서 read읽 read read 。ele.innerHTMLString에 대해 String은 와 완전히 동일합니다.ele(동료)

  • > =>.innerHTML읽기/쓰기를 변경하지 않습니다.

innerText

  • :쓸때: " " "ele.innerText, any, any, any.html reserved special characterString은 처음에 html 형식으로 인코딩된 후 에 저장됩니다.ele.

    • ::<p>[ ]가 됩니다.&lt;p&gt; ele
  • : : " " " 를 때ele.innerText 스트링,

    1. html reserved special character ele읽기 쉬운 텍스트 형식으로 다시 디코딩됩니다.

      • ::&lt;p&gt; ele 돌아오다<p>의 스트링에
    2. any (유효한)html tag ele삭제되어 버립니다.따라서, 이 텍스트는 「문자의 텍스트」가 됩니다.

      • ::if <em>you</em> can ele될 것이다if you can의 스트링에
      • 인 '무효'에 html tag

        • html tag원래는ele 코드..innerText그는는 ?떻 ?? ????

          ('이 있는 )html tag원래는)는 일이 는 안 된다.

        • 잘못 쓸 요.html tag타타에 .innerHTML (생으로) (로ele이될 수 있습니다.-- 그 -- 、 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 。

      • 이것을 순서 [1.][2.]로 하지 말아 주세요.아니오, 순서 [1.][2.]가 동시에 실행됩니다.

        -- 즉, [1.]의 디코딩된 문자가 변환 후에 새로운 태그를 형성할 경우 [2.]는 그것을 삭제하지 않습니다.

        (-- [2 . ]는, 다음의 문자에 대해 고려합니다.ele" " " " " " " )

    3. 그런 다음 String에 저장됩니다.


jsfiddle: 설명 포함

  • (^ 여기에는 console.log의 js 파일 및 + 출력에 대한 코멘트에 더 많은 설명이 포함되어 있습니다.

    아래는 간단한 표시로, 출력도 있습니다.

    (자신이 직접 코드를 시험해 보고, 내 설명이 100% 정확하다는 보장은 없습니다.)

<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite"></p>
<p id="textWrite"></p>
// > @basic (simple)
// read
var ele_mainContent = document.getElementById('mainContent');
alert(ele_mainContent.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.        // >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_mainContent.innerText); // This is a sample sentennce for Reading.                         // >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"

// write
var str_WriteOutput = "Write <strong>this</strong> sentence to the output.";
var ele_htmlWrite = document.getElementById('htmlWrite');
var ele_textWrite = document.getElementById('textWrite');
ele_htmlWrite.innerHTML = str_WriteOutput;
ele_textWrite.innerText = str_WriteOutput;

alert(ele_htmlWrite.innerHTML); // Write <strong>this</strong> sentence to the output.               // >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_htmlWrite.innerText); // Write this sentence to the output.                                // >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"                     
alert(ele_textWrite.innerHTML); // Write &lt;strong&gt;this&lt;/strong&gt; sentence to the output.   // >" any `html reserved special character` in the String will be **encoded** into html format first               
alert(ele_textWrite.innerText); // Write <strong>this</strong> sentence to the output.               // >" 1. any `html reserved special character` in the `ele` will be **decoded** back into a readable text format,  

// > @basic (more)
// write - with html encoded char
var str_WriteOutput_encodedChar = "What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?";
var ele_htmlWrite_encodedChar = document.getElementById('htmlWrite_encodedChar');
var ele_textWrite_encodedChar = document.getElementById('textWrite_encodedChar');
ele_htmlWrite_encodedChar.innerHTML = str_WriteOutput_encodedChar;
ele_textWrite_encodedChar.innerText = str_WriteOutput_encodedChar;

alert(ele_htmlWrite_encodedChar.innerHTML); // What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?
alert(ele_htmlWrite_encodedChar.innerText); // What if you have <strong>encoded</strong> char in the sentence?
alert(ele_textWrite_encodedChar.innerHTML); // What if you have &amp;lt;strong&amp;gt;encoded&amp;lt;/strong&amp;gt; char in &lt;strong&gt;the&lt;/strong&gt; sentence?
alert(ele_textWrite_encodedChar.innerText); // What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?


// > @note-advance: read then write 
var ele__htmlRead_Then_htmlWrite = document.getElementById('htmlRead_Then_htmlWrite');
var ele__htmlRead_Then_textWrite = document.getElementById('htmlRead_Then_textWrite');
var ele__textRead_Then_htmlWrite = document.getElementById('textRead_Then_htmlWrite');
var ele__textRead_Then_textWrite = document.getElementById('textRead_Then_textWrite');

ele__htmlRead_Then_htmlWrite.innerHTML = ele_mainContent.innerHTML;
ele__htmlRead_Then_textWrite.innerText = ele_mainContent.innerHTML;
ele__textRead_Then_htmlWrite.innerHTML = ele_mainContent.innerText;
ele__textRead_Then_textWrite.innerText = ele_mainContent.innerText;

alert(ele__htmlRead_Then_htmlWrite.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__htmlRead_Then_htmlWrite.innerText); // This is a sample sentennce for Reading.
alert(ele__htmlRead_Then_textWrite.innerHTML); // This is a &lt;strong&gt;sample&lt;/strong&gt; sentennce for Reading.
alert(ele__htmlRead_Then_textWrite.innerText); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__textRead_Then_htmlWrite.innerHTML); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_htmlWrite.innerText); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_textWrite.innerHTML); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_textWrite.innerText); // This is a sample sentennce for Reading.


// the parsed html after js is executed
/*
<html><head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite">Write <strong>this</strong> sentence to the output.</p>
<p id="textWrite">Write &lt;strong&gt;this&lt;/strong&gt; sentence to the output.</p>
<!-- P2 -->
<p id="htmlWrite_encodedChar">What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?</p>
<p id="textWrite_encodedChar">What if you have &amp;lt;strong&amp;gt;encoded&amp;lt;/strong&amp;gt; char in &lt;strong&gt;the&lt;/strong&gt; sentence?</p>
<!-- P3 @note: -->
<p id="htmlRead_Then_htmlWrite">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlRead_Then_textWrite">This is a &lt;strong&gt;sample&lt;/strong&gt; sentennce for Reading.</p>
<p id="textRead_Then_htmlWrite">This is a sample sentennce for Reading.</p>
<p id="textRead_Then_textWrite">This is a sample sentennce for Reading.</p>

</body></html>
*/

언급URL : https://stackoverflow.com/questions/19030742/difference-between-innertext-innerhtml-and-value

반응형