If the requisite is to not know the name of the attribute
which value is the string you are looking for, then you can create an XPath query, which will return you all the elements having an attribute with such value :
//*[@*='value']
unwrapped :
'//' + // from root to anywhere in the tree
'*' + // any kind of node
'[@*' + // with any attribute
' = "value"' // which value is 'value'
']'
var valueToFind = 'find-me';
var query = document.evaluate(`//*[@*='${valueToFind}']`, document, null, XPathResult.ANY_TYPE, null);
var elements = [], el;
while(el = query.iterateNext()){
// in your case you will filter it to not be the original node
// if(el !== original)
elements.push(el);
}
console.log(elements);
<div data-id="find-me"></div>
<div data-id="do-not-find-me"></div>
<div class="find-me"></div>
<div class="do-not-find-me"></div>
<div style="find-me"></div>
<div id="find-me"></div>
And if the goal is to get only the elements with data-*
attributes with such value, then the query is a bit more long :
//*[@*[starts-with(name(), 'data-')] = '${valueToFind}']
unwrapped :
'//' + // from root to anywhere in the tree
'*' + // any kind of node
'[@*' + // with any attribute
'[starts-with(name(), "data-")]' + // which starts with "data-"
' = "value"' // and which value is 'value'
']'
var valueToFind = 'find-me';
var query = document.evaluate(`//*[@*[starts-with(name(), 'data-')] = '${valueToFind}']`, document, null, XPathResult.ANY_TYPE, null);
var elements = [], el;
while(el = query.iterateNext()){
elements.push(el);
}
console.log(elements);
<div data-id="find-me"></div>
<div data-foo="find-me"></div>
<div data-id="do-not-find-me"></div>
<div class="find-me"></div>
<div class="do-not-find-me"></div>
<div style="find-me"></div>
<div id="find-me"></div>
querySelector
– Winded.name
of thedata-*
attribute.css
selectors do not provide a means to select elements by value of attribute alone. – Spotterdata-*
attribute does not have.name
property that is equal to.id
of element at Question. – Spotter