2014-04-01 31 views
1

考慮下面如何在不使用類或ID的情況下選擇相同的屬性?

<body> 
    <div> 
    <a href="http://www.google.com">Google</a> 
    <a href="http://www.gmail.com">Gmail</a> 
    <a href="http://www.fb.com">fb</a> 
    </div> 
</body> 

如果我要選擇<a>標籤給出不使用任​​何類的代碼,並希望他們給不同的屬性,有什麼辦法?

+0

是的,有很多方法。你想用CSS或Javascript來引用它們嗎? –

+0

太棒了。從css.Please告訴我一些。 – learner

+1

@learner您的評論聽起來像是在進行一次技術性訪談:) –

回答

1
a { } // all the links 
a + a { } // second link 
a + a + a { } // third link 

a:first-child { } // first link 
a:last-child { } // last link 
+0

你告訴我很多方法。你能告訴我更多嗎? – learner

0

我想你可以這樣做:

document.body.children[0].children[0] // Google link 
document.body.children[0].children[1] // Gmail link 
document.body.children[0].children[2] // FB link 

然而,這是一個非常糟糕的主意,因爲一旦你改變你的HTML結構,你將不得不重新編寫所有的代碼。

+0

告訴我任何好主意。 :p – learner

+2

這是最好的主意:使用ID。 –

-1

使用jQuery(http://www.jquery.com) 這是著名的JavaScript庫與DOM 前操作:

$("a")選擇所有的鏈接。
$("a:contains['Gmail']")選擇與文本的Gmail

+1

[Vanilla JS](http://vanilla-js.com/)比jQuery更強大。 –

+0

不需要僅僅爲這個任務使用jQuery –

0

如果你想用CSS做鏈接,我會說:

a:nth-of-type(2){color:black;} // Select the second 
a:fist-child { color:red;} // Select the first 
a:last-child { color:blue;} // Select the last 
1

使用CSS,你可以檢查href屬性是這樣的:

a[href^="http://www.g"] { 
    color: red; 
} 

JSFiddle

^=手段 「啓動與此」。 $=表示「以此結束」。 *=的意思是「包含這個」。

0

您可以隨時申報CSS裏面的標籤本身,就像這樣:

<a href="http://iodelta.com" style="color:#0F0; font-weight:bold; display:block;">Link Here</a> 
+0

我想這樣做 CSS不是html。 – learner

+0

這是CSS ...所以你想要什麼? – Joshua

相關問題