How to Get the Id & Title of a Div Element, Using Pure Javascript

I have an element:

<div id="Form" title="Disability Form</div>

I am trying to get both the id and the title, formatted as such:

id: Form
title: Disability Form 

I'm also trying to use pure Javascript. This is what I have been playing with so far:

var x = document.getElementsByTagName("div");

for(i=0; i<= x.length; i++)
{
   console.log(x[i].innerText);
}

Does anyone know how to proceed?

2

2 Answers

Mistakes that you have made

  1. <= should be changed to <
  2. Didn't close the tag properly

To get the id you can use element.id

To get the title you can use element.getAttribute('title')

var x = document.getElementsByTagName("div");

for(i=0; i< x.length; i++)
{
   console.log(x[i].innerText);
   console.log('id : ' + x[i].id);
   console.log('title : ' + x[i].getAttribute('title'));
}
<div id="Form" title="Disability Form"></div>

You can use the el.id to get ID and el.getAttribute('title') to get the title attribute value.

Also you did not close the title attributes tag in your HTML...

let divs = [...document.getElementsByTagName('DIV')]

divs.forEach(div => {
  div.hasAttribute('id') ? console.log(`id: ${div.id}`) : false;
  div.hasAttribute('title') ? console.log(`title: ${div.title}`) : false;
})
<div id="Form" title="Disability Form"></div>
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest