如何在选择器中指定前一个元素的属性?

时间:2016-12-28 11:32:10

标签: javascript html css-selectors

我有一个JS选择器:

"a[title*=Download]"

将找到标题为“下载”的链接。但是,我希望它仅在前一个元素的id属性为例如“P24_MY_ID”时才匹配。如何修改我的第一个查询?它应该是一个行选择器。

更新更多代码:

<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>

1 个答案:

答案 0 :(得分:1)

您可以使用adjacent sibling combinator+

#P24_MY_ID + a[title*=Download]

选择直接跟随一个a[title*=Download]元素的#P24_MY_ID个元素(因为ID必须是唯一的)。

使用示例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>