Home > OS >  getElementsByTagName , anchor tag, adding it to pargraph innerHtml , Show out the href attribute val
getElementsByTagName , anchor tag, adding it to pargraph innerHtml , Show out the href attribute val

Time:07-01

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>

CodePudding user response:

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>

CodePudding user response:

  • 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.
  • Related