简体   繁体   中英

Issue While Getting innerHTML Text Using JavaScript

In the following code I am extracting the innerHTML text of the html element.

if(a.tagName){
if("option"==a.tagName.toLowerCase())
    return a.text.replace(/\u00A0/g," ");
if("select-one"==a.type||"select-multiple"==a.type)
    return this.getSelectBoxText(a,!1);
}
if(this._isIE()||this.isSafariLike()&&!this._isChrome())
    return a.innerText||a.textContent||"";
var b=a.innerHTML;
return!b||-1==b.indexOf("\x3cbr")&&-1==b.indexOf("\x3cBR")?a.textContent:document.createElement?  (b=document.createElement(a.tagName),b.innerHTML=a.innerHTML.replace(/<br[\/]*>/ig," "),b.textContent):a.textContent
};

above code return the correct innerHTML text for all HTML element. There is an issue when any HTML element contain text with special character code eg
<a id="oopID1" href="...">OOP &ndash; Java</a> <a id="oopID1" href="...">OOP &ndash; Java</a> [in page is show " OOP - Java "].

then it does not return the actual rendered text (mean "OOP - Java").

How could I get the actual value which is getting displayed in the page.

Thanks in advance.

[NOTE : I don't want to use jQuery.]

Use textContent to retrieve the text content of your element:

document.getElementById("oopID1").textContent

see fiddle HERE

Useful links:

textContent documentation

innerHTML documentation

innerText vs innerHTML

使用innerText而不是innerHTML因为前者将值作为文本,而后者将其作为标记。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM