1

I need write a function called that takes in one argument, which is a list of elements. In the list of elements there's ONE element that has an ID,but I don't know what's the ID called. The function should change the inner text of the element to be the value of the ID. Example:

<div><div/>
<div><div/>
<div><div/>
<div id="special"><div/>
<div><div/>
let divs = querySelectorAll('div')
findId(divs)

What it should do :

<div><div/>
<div><div/>
<div><div/>
<div id="special">special<div/>
<div><div/>

I have tried using innerhtml but I do not know how to go about doing it,as the id is unknown.
Please help out.

muhammad
  • 245
  • 1
  • 13

5 Answers5

2

Something like this;

function change(divs){
  divs.forEach((div) => {
    if(div.id){
      div.innerHTML = div.id;
    }
  })
}

let divs = document.querySelectorAll('div');
change(divs);
<div></div>
<div id="special"></div>
<div></div>
<div></div>
Miller
  • 311
  • 1
  • 5
  • ES6 syntax is actually faster. https://stackoverflow.com/questions/50844095/should-one-use-for-of-or-foreach-when-iterating-through-an-array –  Oct 03 '19 at 19:52
  • Is that worth a downvote? Something that will never be noticeable... Only work on your performance once its needed ( on this level ), otherwise you will have a hard time. Downvote when something is just not a correct answer, not because of your preference. Being helpful here should be a good thing, not a bad one. – Miller Oct 03 '19 at 19:55
2

To determine if the element has an ID, you can just use the hasAttribute() method:

// Array.prototype.slice.call() is an easy way to turn the NodeList document.querySelector returns into an array.
const divs = Array.prototype.slice.call(document.querySelectorAll('div'));

const haveIds = divs.filter(element =>
  element.hasAttribute('id')
);

console.log(haveIds);
<div>A</div>
<div>B</div>
<div id="me">C</div>
<div>D</div>
<div id="me-too">E</div>

Alternatively, you can also use querySelector itself to determine it as well:

const withIds = document.querySelectorAll('div[id]');

console.log(withIds);
<div>A</div>
<div>B</div>
<div id="me">C</div>
<div>D</div>
<div id="me-too">E</div>

That [id] part basically means "if it has the attribute ID".

Regardless which method you choose, then you just loop through and set the innerText to their ID:

const withIds = Array.prototype.slice.call(document.querySelectorAll('div[id]'));

withIds.forEach(element => element.innerText = element.id);
<div>A</div>
<div>B</div>
<div id="me">C</div>
<div>D</div>
<div id="me-too">E</div>
samanime
  • 25,408
  • 15
  • 90
  • 139
  • Just pointing out that you don't need to do the slice on the querySelectorAll in that last snippet; NodeList has a forEach method that works the same as Array :) – IceMetalPunk Oct 03 '19 at 20:30
  • True, though I still generally prefer to convert it to an array because `NodeList` has a very limited subset of Array's methods, so if your case isn't as simple as just calling `forEach()` you'll want to convert it. – samanime Oct 04 '19 at 06:57
  • I'm curious about whether spreading it is more, less, or equally efficient as calling slice for the conversion.... I'm going to test this! *Message from the future:* Slice is apparently twice as fast as spread. Go figure. – IceMetalPunk Oct 04 '19 at 15:10
2

modern syntax:

let divs = document.body.querySelectorAll("div");
for (const div of divs) {
  if (div.hasAttribute("id")) {
    const id = div.id;
    div.innerHTML = id;
  }
}
2

Iterate through list of elements and check them by css selector: .matches('div[id]'). Use textContent of found one.

let divs = document.querySelectorAll('div');
let result = findId(divs);
console.log(result);


function findId(list) {
    for (var i = 0; i < list.length; i++) {
      if (list[i].matches('div[id]')) {
        return list[i].textContent;
      }
    }
    return null;
}
Alex Vovchuk
  • 2,828
  • 4
  • 19
  • 40
1

const theDivs = document.querySelectorAll('div');

if (theDivs) {
  theDivs.forEach(function(el) {

  if (el.id) {
    el.innerHTML = el.id;
  }

  });
} else {
  alert('Sorry, no divs found buddy');
}
div {
  padding: 1rem;
  border: lightgray 1px dotted;
  width: 10rem;
}
<div></div>
<div></div>
<div id="special"></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Chris W.
  • 22,835
  • 3
  • 60
  • 94