简体   繁体   中英

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

when I saw this example , it used getElementsByTagName() method to bring all anchor tags then using the index [0] to bring the first element inside this HTMLCollection. assign it to x variable. if I console.log(x) I will get what is expected the first anchor tag in my HTML DOM. but if I assign this X to a paragraph using innerHTML , the result will show the href value which inside the anchor , I expected to add the whole anchor tag as HTML element and show inside the paragraph the content of it which is in this example 'Hello world'. any explanation why this is happening? Thank you.

 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>

When you assign x to innerHTML , it's converted to a string. Converting a DOM element to a string doesn't return the full HTML of the element; in most cases it returns a string like [object HTMLDivElement] , but anchors override this and returns the href value (see HTMLAnchorElement.toString() .

To get the full HTML of an element, you can use the outerHTML property.

 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>

  • innerHTML takes string input, and converts HTML tag to valid tags and leave content as it is. So,here <a> tag is converted to a tag that y you are not able to print hole <a href="link">text<a/a> it's only print text as an anchortag. for more information visit this page .

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