I need to manipulate certain elements having some ids using javascript. I do not control the code so unfortunately I cannot rewrite the code with unique ids. For example:
<div id="abc">
<p class="xyz">10</p>
</div>
<div id="abc">
<p class="xyz">20</p>
</div>
The content inside the p tags is guaranteed to be unique. So, I need to perform some operations on the basis of the content inside the p tags.
But if I use DOM to select by id, which of the div would be selected and how do I ensure that I select the required element ?
Obviously, having unique IDs is optimal, however, in the case that it is unavoidable, you can work with it like so:
var abcs = document.querySelectorAll("#abc");
abcs[0].querySelector(".xyz").style.background = "green";
abcs[1].querySelector(".xyz").style.background = "red";
<div id="abc">
<p class="xyz">10</p>
</div>
<div id="abc">
<p class="xyz">20</p>
</div>
Note the use of document.querySelectorAll()
instead of document.getElementById()
. That is because querySelectorAll
will grab all matching elements, whereas getElementById()
will only grab the first one.
var abcs = document.querySelectorAll("#abc");
function setAbcByContent(contentValue, color) {
abcs.forEach(function (elem) {
if (elem.querySelector(".xyz").innerText === contentValue) {
elem.style.background = color;
}
});
}
setAbcByContent("10", "green");
setAbcByContent("20", "red");
<div id="abc">
<p class="xyz">10</p>
</div>
<div id="abc">
<p class="xyz">20</p>
</div>