Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector works, getElementById does not

I'm working with new web-component using Polymer. In this new component, I use javascript, creating Nodes and Attributes dinamically when xhr == 200. When I've created all elements, I retrieve some data and do analysis. In this analysis I want get all nodes with specific id, like this:

var selection = document.querySelectorAll("#container > div");
for(var i = 0; i < selection.length; i++){
    var data1 = document.getElementById("span#vth" + selection[i].id);
    var data2 = document.querySelector("span#vta" + selection[i].id);
    console.log("data1 with id " + selection[i].id + ": " + data1);
    console.log("data2 with id " + selection[i].id + ": " + data2.innerHTML);
}

With document.getElementById does not work, it returns null. document.querySelector does work. Someone can explainme why? Thanks on advance!

like image 978
Jnmgr Avatar asked Nov 01 '25 23:11

Jnmgr


1 Answers

Your syntax is wrong.

var data1 = document.getElementById("span#vth" + selection[i].id);

should be

var data1 = document.getElementById('vth'+selection[i].id);

An ID should only ever be used once, so no need for the element specificity, and you don't include the hash #because that's not part of the ID name.

document.querySelector() and document.querySelectorAll() function similarly to the jQuery selector engine, but the getElementById() and getElementByClassName() just take in the string representation, no need for . or # to preface.

like image 68
tdc Avatar answered Nov 03 '25 12:11

tdc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!