E_A
E_A

Reputation: 131

How to get all of the element ids on the same time in javascript?

I want to get all the ids names on a particular page and change it base on a particular name

Is it possible?

I tried so far:

function get_all()
{
    var esther = document.getElementById(*);
    document.getElementById("bod").value = esther;
}

Upvotes: 1

Views: 2823

Answers (3)

Rounin
Rounin

Reputation: 29493

If you want to display the list of ids on the page, you can grab all the elements on the page using:

let allElementsWithIds = [... document.querySelectorAll('[id]')];

And then you can create a <ul> and populate it with the ids from each of those elements, before appending it to the document body.

N.B. Note that paragraph2 and link1 in the example below do not have ids, so they do not appear in the list of ids.

Working Example:

// Get all Elements with Ids
let allElementsWithIds = [... document.querySelectorAll('[id]')];

// Initialise List of Ids
let listOfIds = document.createElement('ul');
listOfIds.classList.add('top-right');

// Populate List of Ids
allElementsWithIds.forEach((element) => {

  let newListItem = document.createElement('li');
  newListItem.textContent = element.id;
  listOfIds.appendChild(newListItem);
});

// Append List Of Ids to Document Body
document.body.appendChild(listOfIds);
.top-right {
  position: absolute;
  top: 24px;
  right: 24px;
}
<h1 id="heading1">This is Heading 1</h1>
<p id="paragraph1">This is Paragraph 1</p>
<p>This is Paragraph 2</p>
<p id="paragraph3">This is Paragraph 3</p>

<nav id="nav1">
<a href="link1">This is Link 1</a> |
<a id="link2" href="link2">This is Link 2</a>
</nav>

Upvotes: 1

OPTIMUS PRIME
OPTIMUS PRIME

Reputation: 1325

console.log( getIds_1() );
console.log( getIds_2() );

function getIds_1(){
  let id = document.querySelectorAll('[id]');
  
  return [].slice.call(id).map(function(elem){
    return elem.id;
  }).join(", ");
}

function getIds_2(){
  return [...document.querySelectorAll('[id]')].map(e => e.id).join(", ");
}
<div id="bubu"></div>
<div id="moo"></div>
<div id="test"></div>
<div id="example"></div>
<div id="id_007"></div>

Upvotes: 0

Armedin Kuka
Armedin Kuka

Reputation: 675

This should do the job

document.querySelectorAll('*[id]')

Upvotes: 4

Related Questions