简体   繁体   中英

Add style of class only for first element of UL (JS or jquery)

I have page where ul is displayed on the page as shown below:

<ul>
    <li style="width: 158px;">A</li>
    <li style="width: 158px;">B</li>
    <li style="width: 158px;">C</li>
</ul>

Can I add style border or class only for first element A (using JS or jQuery or any other framework)?

Using jQuery to add a class to the first element of the <ul/>

$(document).ready(function(){
    $('ul li:first').addClass('has-border');
});

Demo: https://jsfiddle.net/e8pvj9hb/

This will target the first occurrence of an <li> and apply a border to it.

document.querySelectorAll('li')[0].style.border = '1px solid #ccc';

If you want to only target the first <li> with a specific class, you can change the ('li') to something like ('li.someClass') and put a class on the element you wish to target.

If you also wish to target all of your li elements, then use something like this.

document.querySelectorAll('li').forEach(function(x) { x.style.border = '1px solid #ccc'; })

If you prefer CSS:

ul li:first-child {
    border: solid 1px red;
}

If you prefer JavaScript:

document.querySelectorAll('li')[0].style.border = '1px solid red';

If you prefer jQuery:

$('ul li').first().css('border', '1px solid red');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM