• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

227
Views
getElementsByTagName , anchor tag, adding it to pargraph innerHtml , Show out the href attribute value only !!! any explanation?

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>

about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 3 years ago · Juan Pablo Isaza Report

0

  • 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.
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error