Skip to content
Advertisement

Get the ID of an element where the class contains a given string

I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something. I’m not sure if there’s a better way to do it than I currently am, but having looked around nothing fits exactly the need I have. The code I currently have is, where I am looking for a div element whose class contains the string “one” but is not limited to that. Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):

$idToMove = document.querySelectorAll('div[class^="one"]');
        alert($idToMove);

Advertisement

Answer

document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.

1) Use .querySelector instead:

// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);

2) Access the first element in the returned list:

// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);

Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.

Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:

[attr~=value] Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly “value”.

[attr^=value] Represents an element with an attribute name of attr and whose first value is prefixed by “value”.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement