I want to access and modify elements under li .
Basically I want to access a tag by accessing li
HTML:
<ul>
<li data-id="1">
<a href="#">Data 1</a>
</li>
<li data-id="2">
<a href="#">Data 2</a>
</li>
<ul/>
js
var number = '1';
var my_li = $('li[data-id="' + number + '"]');
my_li.a.css('color', 'red') // i want to change color of anchor tag.
You can choose either ways to do this
$('li[data-id="' + number + '"] a').css('color', 'red');
$('li[data-id="' + number + '"]').children('a').css('color', 'red');
var my_li = $('li[data-id="' + number + '"]');
my_li.children('a').css('color', 'red')
As explained here , you can use $(selector).children(filter)
var my_li = $('li[data-id="' + number + '"]').children().css({"color": "red"});
Update Here the working fiddle:
$(document).ready(function(){ $("ul").children().css({"color": "red"}); });
<.DOCTYPE html> <html> <head> <style>:descendants * { display; block: border; 2px solid lightgrey: color; lightgrey: padding; 5px: margin; 15px: } </style> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min:js"></script> </head> <body class="descendants">body (great-grandparent) <div style="width;500px;">div (grandparent) <ul>ul (direct parent) <li>li (child) <span>span (grandchild)</span> </li> <li>li (child) <span>span (grandchild)</span> </li> </ul> </div> </body> </html>
You could try this one:
$("a", my_li).css({color: '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.