This request:
someTag.querySelector("tbody > tr[my-attr='333']").children
returns an array of "td". Some of them have an attribute "attribute1". How can I find a "td" among which has the attribute1="123"?
I've tried different approaches but hasn't been successfull. For example:
someTag.querySelector("tbody > tr[my-attr='333'][attribute1='123']")
returns null
This request:
someTag.querySelector("tbody > tr[my-attr='333']").children
returns an array of "td". Some of them have an attribute "attribute1". How can I find a "td" among which has the attribute1="123"?
I've tried different approaches but hasn't been successfull. For example:
someTag.querySelector("tbody > tr[my-attr='333'][attribute1='123']")
returns null
Share Improve this question edited Dec 11, 2015 at 9:51 Alan Coromano asked Dec 11, 2015 at 9:12 Alan CoromanoAlan Coromano 26.1k55 gold badges140 silver badges215 bronze badges 3- add some samplecode... jsfiddle or the implemented source preview – Dwza Commented Dec 11, 2015 at 9:14
-
3
If you're finding the
td
s,tbody > tr[my-attr='333'] td[attribute1='123']
? Your secondtbody > tr[my-attr='333'][attribute1='123']
is findingtr
that hasmy-attr='333'
andattribute1='123'
it has not condition check on the childtd
s. – fuyushimoya Commented Dec 11, 2015 at 9:14 -
may be
tbody > tr[my-attr='333'] > td[attribute1='123']
– Suresh Ponnukalai Commented Dec 11, 2015 at 9:15
3 Answers
Reset to default 3You should use querySelectorAll
to get all the td
with attribute1='123'
.
Check this snippets:
var tds = document.querySelectorAll("tbody > tr[my-attr='333'] td[attribute1='123']");
tds[0].innerHTML = "JavaScript"
tds[1].innerHTML = "JQuery"
<table>
<tbody>
<tr my-attr='333'>
<td attribute1='123'>January</td>
<td>$100</td>
</tr>
<tr my-attr='333'>
<td attribute1='123'>February</td>
<td>$80</td>
</tr>
<tr my-attr='333'>
<td attribute1='124'>March</td>
<td>$80</td>
</tr>
<tr my-attr='333'>
<td attribute1='124'>April</td>
<td>$80</td>
</tr>
</tbody>
</table>
Update:
As per the attached sample, script as follows
var tds = document.querySelectorAll("tbody > tr[my-attr='333'] td[attribute1='123']");
for (var i = 0; i < tds.length; i++) {
tds[i].style.backgroundColor = '#888'
}
FIDDLE DEMO
This works:
var res = document.querySelectorAll("tbody > tr[my-attr='333'] > [attribute1='123']")
console.log(res)
<table>
<tbody>
<tr my-attr="333">
<td attribute1="123">Cell</td>
<td attribute1="123">Cell</td>
</tr>
<tr></tr>
</tbody>
</table>
edit: uses querySelectorAll
because the OP wants to find multiple nodes.
There are more than one problem.
First you use querySelector
this will cause that you will only retrive one element (the first that matches).
Use querySelectorAll
instead.
Than you use children
. In your sample the TD's dont have children so you will never even get one result. Even if the selector is correct. What brings me to the last point
This is the correct selector:
tbody > tr[my-attr='333'] > [attribute1='123']
Here you have a working Fiddle