Pablo
Pablo

Reputation: 29519

How to specify previous element's attribute in selector?

I have a JS selector:

"a[title*=Download]"

which will find link titled "Download". However, I would like it to match only when previous element's id attribute is for example "P24_MY_ID". How can I modify my first query? It should be one line selector.

UPDATE more code:

<input type="file" id="P24_MY_ID" name="p_t32" class="file"  size="30" />&nbsp;<a href="apex_util.get_blob_file?a=442&s=1281349283063&p=24&d=49830111238173502&i=163125708564179080&p_pk1=10980&p_pk2=&p_ck=67989B0EF83EF635B71455E04793731B&p_content_disposition=attachment" title="Download 1KB" alt="Download 1KB">Download</a>

Upvotes: 0

Views: 37

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

You can use the adjacent sibling combinator, +:

#P24_MY_ID + a[title*=Download]

That selects the one a[title*=Download] element that directly follows the one #P24_MY_ID element (as IDs have to be unique).

Live example with your sample HTML:

var link = document.querySelector("#P24_MY_ID + a[title*=Download]");
link.style.color = "red";
console.log("Total matching: ", document.querySelectorAll("#P24_MY_ID + a[title*=Download]").length);
Matches this link only (turning it red):
<br><input type="file" id="P24_MY_ID" name="p_t32" class="file"  size="30" />&nbsp;<a href="apex_util.get_blob_file?a=442&s=1281349283063&p=24&d=49830111238173502&i=163125708564179080&p_pk1=10980&p_pk2=&p_ck=67989B0EF83EF635B71455E04793731B&p_content_disposition=attachment" title="Download 1KB" alt="Download 1KB">Download</a>
<hr>
And not for instance this one:
<br><a href="apex_util.get_blob_file?a=442&s=1281349283063&p=24&d=49830111238173502&i=163125708564179080&p_pk1=10980&p_pk2=&p_ck=67989B0EF83EF635B71455E04793731B&p_content_disposition=attachment" title="Download 1KB" alt="Download 1KB">Download</a>

Upvotes: 1

Related Questions