![](/img/trans.png)
[英]How can I replace the text in an HTML tag but not in an href link?
[英]How can I print hole HTML tag using javascript. like how to print thi hole line (<a href="link">text</a>) instead of just text as a link
當我看到這個例子時,它使用getElementsByTagName()
方法來帶入所有錨標記,然后使用索引 [0] 將第一個元素帶入這個 HTMLCollection。 將其分配給 x 變量。 如果我console.log(x)
我將得到我的 HTML DOM 中的第一個錨標記。 但是如果我使用innerHTML
將此 X 分配給一個段落,結果將顯示錨點內的 href 值,我希望將整個錨點標記添加為 HTML 元素並在段落內顯示它的內容,即本例中的內容你好世界'。 任何解釋為什么會這樣? 謝謝你。
const x = document.getElementsByTagName('a')[0]; console.log(x); // will print out the anchor tag element document.getElementById('demo').innerHTML = x; // will add the href attribute value of the anchor only, But I expected that I will get the text 'hello world'
<!DOCTYPE html> <html> <body> <a href="https://www.w3schools.com/html/">hello world</a> <a href="https://www.w3schools.com/css/">Welcome</a> <p id="demo"></p> </body> </html>
當您將x
分配給innerHTML
時,它會轉換為字符串。 將 DOM 元素轉換為字符串不會返回元素的完整 HTML; 在大多數情況下,它會返回一個類似[object HTMLDivElement]
的字符串,但錨會覆蓋它並返回href
值(請參閱HTMLAnchorElement.toString()
。
要獲取元素的完整 HTML,可以使用outerHTML
屬性。
const x = document.getElementsByTagName('a')[0]; console.log(x); // will print out the anchor tag element document.getElementById('demo').innerHTML = x.outerHTML; // will add the href attribute value of the anchor only, But I expected that I will get the text 'hello world'
<!DOCTYPE html> <html> <body> <a href="https://www.w3schools.com/html/">hello world</a> <a href="https://www.w3schools.com/css/">Welcome</a> <p id="demo"></p> </body> </html>
HTML tag
轉換為有效標記並保持內容不變。 所以,這里<a>
標簽被轉換成一個標簽,你不能打印孔<a href="link">text<a/a>
它只是打印文本作為錨標簽。 欲了解更多信息,請訪問 此頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.