2014-04-01 30 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

相关问题