如何向HTML元素添加“class”属性?

时间:2011-11-10 19:31:32

标签: c# asp.net string append

我有以下HTML。我想将class="last"个属性添加到每个列表中的最终li元素中。我怎样才能做到这一点?

<div class="gpbscol">
<ul class="listl">
    <li>ACCESSORIES</li>
    <li>AMPLIFIERS</li>
    <li>ANALOG AUDIO PROCESSING</li>
    <li>MICROPHONE PREAMPLIFIERS</li>
    <li>MICROPHONES</li>
    <li>SPEAKERS/MONITORS</li>
    <li>STUDIO</li>
    <li>DIGITAL AUDIO PROCESSING</li>
    <li>CONSOLES, MIXERS</li>
    <li>DAWS/PERIPHERALS</li>
</ul>
</div>
<div class="audio"> 
   <ul class="listl">
    <li>DAWS/PERIPHERALS</li>
    <li>LOUDSPEAKERS — FOH</li>
    <li>RECORDERS/PLAYERS</li>
    <li>HEADPHONES</li>
    <li>MICROPHONES - WIRELESS CONVERTERS</li>
    <li>NETWORK AUDIO / CONTROL / SNAKES</li>
    <li>COMPUTER AUDIO INTERFACES</li>
    <li>INTERCONNECTS</li>
    <li>LOUDSPEAKERS — STAGE MONITORS</li>
    <li>ACOUSTIC TREATMENT</li>
    <li>MI PRODUCTS</li>
   </ul>
</div>

所以最后的元素可能是

<li class="last">MI PRODUCTS</li>

5 个答案:

答案 0 :(得分:2)

我会成为造型问题。如果我没有客户端代码选项,我会选择CSS样式。你可以考虑这个:

ul.listl li:last-child { }

答案 1 :(得分:1)

这对jQuery更容易:

$(function(){
    $("ul.listl li:last").addClass("last");
});

这就是全部,伙计们:)

答案 2 :(得分:0)

我同意@JohnHartsock但是如果你想按照自己的方式去做,你可以使用各种库来帮助你查询html元素(DOM)。

  1. Fizzler
  2. Sharp-Query
  3. HTML Agility Pack

答案 3 :(得分:0)

string[] g=@"<div class=""gpbscol"">
<ul class=""listl"">
    <li>ACCESSORIES</li>
    <li>AMPLIFIERS</li>
    <li>ANALOG AUDIO PROCESSING</li>
    <li>MICROPHONE PREAMPLIFIERS</li>
    <li>MICROPHONES</li>
    <li>SPEAKERS/MONITORS</li>
    <li>STUDIO</li>
    <li>DIGITAL AUDIO PROCESSING</li>
    <li>CONSOLES, MIXERS</li>
    <li>DAWS/PERIPHERALS</li>
</ul>
</div>
<div class=""audio""> 
   <ul class=""listl"">
    <li>DAWS/PERIPHERALS</li>
    <li>LOUDSPEAKERS — FOH</li>
    <li>RECORDERS/PLAYERS</li>
    <li>HEADPHONES</li>
    <li>MICROPHONES - WIRELESS CONVERTERS</li>
    <li>NETWORK AUDIO / CONTROL / SNAKES</li>
    <li>COMPUTER AUDIO INTERFACES</li>
    <li>INTERCONNECTS</li>
    <li>LOUDSPEAKERS — STAGE MONITORS</li>
    <li>ACOUSTIC TREATMENT</li>
    <li>MI PRODUCTS</li>
   </ul>
</div>".Split(new string[]{"<li>"});

g[g.length-1]=g[g.length-1].replace("<li>","<li class='last' >");

string newString=String.Join("", g);

答案 4 :(得分:0)

最简单的,这是使用HtmlAgilityPack;

TextWriter text = new StringWriter();
string set =  [html here];
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(set);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//li[last()]");
HtmlAttribute attr;
attr = node.SetAttributeValue("class", "last");
doc.Save(text);
return text;
无论如何,谢谢大家的帮助。