I am learning the basics of JQuery, and can't solve this problem: given 3 green <li> elements turn 1-st and 3-rd elements to red color, and the 2-nd element to orange.
Code:
<!DOCTYPE html>
<html>
<head>
<title>element</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css" media="screen">
ul li{color: green;}
</style>
</head>
<body>
<ul>
<li>text 1</li>
<li>text 2</li>
<li>text 3</li>
</ul>
<script>
var lis = $("ul li").css("color", "red");
</script>
</body>
</html>
I was able to make all the elements red, but I can't make the 2-nd orange: lis[1].css("color", "orange"); doesn't work.
You are calling css on DOM object instead of jQuery object as indexer [] gives you DOM object You need eq() instead of indexer
Live Demo
lis.eq(1).css("color", "orange");
Description: Reduce the set of matched elements to the one at the
specified index.
You can also use :eq() directly in the selector
$("ul li:eq(1)").css("color", "red");
You can achieve it with pure CSS by applying :nth-child selector:
ul li:nth-child(2) {
color: red;
}
Fiddle Demo
Since you are learning jQuery, you can use the :even selector:
var lis = $('ul li');
lis.filter(':even').css('color', 'red'); // Zero based indexing selects 0 and 2
lis.filter(':odd').css('color', 'orange'); // Selects 1
Note, from the docs:
Because :even is a jQuery extension and not part of the CSS specification, queries using :even cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :even to select elements, first select the elements using a pure CSS selector, then use .filter(":even").
please write your code in document.ready() and use eq
for all element
$(document).ready(function(){
$("ul li").css("color", "red");
});
for particluar element
$(document).ready(function(){
$("ul li:eq(0)").css("color", "red"); //for first element
$("ul li:eq(1)").css("color", "red");//for second element
$("ul li:eq(2)").css("color", "red");//for third element
});
If you want to select only first element than use this...
use CSS pesudo selector :first-of-type
$("li:first-of-type").css("color","orange");
or you can use jQuery built in selector
$("li:first").css("color","orange");
Both will work fine...but the jQuery method is relatively slower than CSS pesudo selector
so use the first one for better performance
now if you want to select any other index then use .eq()
$(selectorName.eq(index)).css(...);
Related
I am learning the basics of JQuery, and can't solve this problem: given 3 green <li> elements turn 1-st and 3-rd elements to red color, and the 2-nd element to orange.
Code:
<!DOCTYPE html>
<html>
<head>
<title>element</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css" media="screen">
ul li{color: green;}
</style>
</head>
<body>
<ul>
<li>text 1</li>
<li>text 2</li>
<li>text 3</li>
</ul>
<script>
var lis = $("ul li").css("color", "red");
</script>
</body>
</html>
I was able to make all the elements red, but I can't make the 2-nd orange: lis[1].css("color", "orange"); doesn't work.
You are calling css on DOM object instead of jQuery object as indexer [] gives you DOM object You need eq() instead of indexer
Live Demo
lis.eq(1).css("color", "orange");
Description: Reduce the set of matched elements to the one at the
specified index.
You can also use :eq() directly in the selector
$("ul li:eq(1)").css("color", "red");
You can achieve it with pure CSS by applying :nth-child selector:
ul li:nth-child(2) {
color: red;
}
Fiddle Demo
Since you are learning jQuery, you can use the :even selector:
var lis = $('ul li');
lis.filter(':even').css('color', 'red'); // Zero based indexing selects 0 and 2
lis.filter(':odd').css('color', 'orange'); // Selects 1
Note, from the docs:
Because :even is a jQuery extension and not part of the CSS specification, queries using :even cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :even to select elements, first select the elements using a pure CSS selector, then use .filter(":even").
please write your code in document.ready() and use eq
for all element
$(document).ready(function(){
$("ul li").css("color", "red");
});
for particluar element
$(document).ready(function(){
$("ul li:eq(0)").css("color", "red"); //for first element
$("ul li:eq(1)").css("color", "red");//for second element
$("ul li:eq(2)").css("color", "red");//for third element
});
If you want to select only first element than use this...
use CSS pesudo selector :first-of-type
$("li:first-of-type").css("color","orange");
or you can use jQuery built in selector
$("li:first").css("color","orange");
Both will work fine...but the jQuery method is relatively slower than CSS pesudo selector
so use the first one for better performance
now if you want to select any other index then use .eq()
$(selectorName.eq(index)).css(...);
I have an unordered list and the index of an li tag in that list. I have to get the li element by using that index and change its background color. Is this possible without looping the entire list? I mean, is there any method that could achieve this functionality?
Here is my code, which I believe would work...
<script type="text/javascript">
var index = 3;
</script>
<ul>
<li>India</li>
<li>Indonesia</li>
<li>China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
<script type="text/javascript">
// I want to change bgColor of selected li element
$('ul li')[index].css({'background-color':'#343434'});
// Or, I have seen a function in jQuery doc, which gives nothing to me
$('ul li').get(index).css({'background-color':'#343434'});
</script>
$(...)[index] // gives you the DOM element at index
$(...).get(index) // gives you the DOM element at index
$(...).eq(index) // gives you the jQuery object of element at index
DOM objects don't have css function, use the last...
$('ul li').eq(index).css({'background-color':'#343434'});
docs:
.get(index) Returns: Element
Description: Retrieve the DOM elements matched by the jQuery object.
See: https://api.jquery.com/get/
.eq(index) Returns: jQuery
Description: Reduce the set of matched elements to the one at the specified index.
See: https://api.jquery.com/eq/
You can use jQuery's .eq() method to get the element with a certain index.
$('ul li').eq(index).css({'background-color':'#343434'});
You can use the eq method or selector:
$('ul').find('li').eq(index).css({'background-color':'#343434'});
There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:
<script>
// css selector that describes what you need:
// ul li:nth-of-type(3)
var selector = 'ul li:nth-of-type(' + index + ')';
$(selector).css({'background-color':'#343434'});
</script>
There are other selectors that you may use with jQuery to match any element that you need.
You could skip the jquery and just use CSS style tagging:
<ul>
<li>India</li>
<li>Indonesia</li>
<li style="background-color:#343434;">China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
$('button').click(function(){
$('ul').find('li:nth-child(2)').css('color', '#f00')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul>
<button>Draw it</button>
I wanna get element <li>Ralph</li> by this way: Providing a negative number indicates a position starting from the end of the set, just like .eq(-2):
$('ul').find('li:nth-child(-2)').css('color', '#f00')
Is it possible? If not, is there a way to override nth-child() function?
Use :nth-last-child(2).
This is a standards compliant selector, so it also works with .querySelectorAll and in your CSS.
$('ul').find('li:nth-last-child(2)').css('color', '#f00')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul>
<button>Draw it</button>
This will also work if there are multiple ul elements. Non-standard selectors like jQuery's .eq() will only give you the second to last element out of the entire set.
Try the :nth-last-child() selector. It counts up from the last child, starting from 1 as the last.
$('button').click(function(){
$('ul').find('li:nth-last-child(2)').css('color', '#f00')
});
First of all, sorry if this is a simple question. I am new to jQuery and I want to know how can I check if an element exists and if it does, change the css property.
Here is what I mean: I have the following list:
<ul class="element-rendered">
<li class="element-choice">Item A</li>
<li class="select-inline">Item B</li>
</ul>
I want to know how can I check if the class select-inline exists inside element-rendered and if it does, how can I change the css background of element-choice to blue?
I created a fiddle to reproduce this example.
Again sorry if this is a simple question but I am new to jQuery.
You can use .length to check if the element exists in DOM.
$('.element-rendered .select-inline') will select all the elements having class select-inline inside the element with class element-rendered. .length on selector will return the number of matched elements. So, number greater that one, means the element exists. Then you can use .css to set inline styles.
Demo
if ($('.element-rendered .select-inline').length) {
$('.element-choice').css('background', 'blue');
}
.element-choice {
width: 100%;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<ul class="element-rendered">
<li class="element-choice">Item A</li>
<li class="select-inline">Item B</li>
</ul>
I'll also recommend you to use class in CSS and add it to the element by using addClass.
Demo
var eR = $(".element-rendered");
if (eR.find(".select-inline").length > 0){
eR.find(".element-choice").css("color", "blue");
}
This would work for your specific example.
Find the select-line element which is a child of element-rendered.
The find all of the sibling elements with class element-choice and apply the css.
$('.element-rendered>.select-inline').siblings('.element-choice').css('background','blue')
http://jsfiddle.net/SeanWessell/hjpng78s/3/
To check if element exists could use .is() , or as suggested by #Tushar .length
var container = $(".element-rendered");
// alternatively `!!$(".select-inline", container).length`
$(".select-inline", container).is("*")
&& $(".element-choice", container).css("background", "blue");
jsfiddle http://jsfiddle.net/hjpng78s/6/
Demo
if($(".element-rendered .select-inline")[0])
$(".element-rendered .select-inline").css("background-color","red");
How can I check if the class select-inline exists inside element-rendered and if it does, how can I change the css background of element-choice to blue?
if ( $(".element-rendered > .select-inline").length ) {
$(".element-rendered > .element-choice").css({
'background-color': 'blue'
});
}
Docs:
Find the number of elements in the jQuery object.
Set one or more CSS properties for the matched element
CSS selector :not() is not working and jQuery :not does.
Consider this structure:
<div class="main">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<div>
<div class="doc-view">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</div>
</div>
And this simple CSS:
li:not(.doc-view li) {
color:green;
}
And a little of jQuery here:
$('li:not(.doc-view li)').css('color','red');
As you can see, selectors are the same. But if you play with jsFiddle, you will see, that are not the same. jQuery selector targets elements, CSS does not.
http://jsfiddle.net/LL429/3/
EDIT:
The question is:
How to target all <li>s on the page, except those which are in .doc-view container?
This is because they mean different things. Let's start with the CSS.
li:not(.doc-view li)
This means select all list items, but not those that have descendants that have the class doc-view with a list item descendant. Your code has none of those, plus only simple selectors are allow to be used with :not(), so the selector is invalid anyway.
Now for the jQuery.
$('li:not(.doc-view li)')
This says select all list items, but do not include in that collection any elements with the class doc-view with a list item descendant. This works because it first select all list items, and then removes the matching group of elements that fit the :not(.doc-view li) selector.
CSS selectors != jQuery selectors.
jQuery uses Sizzle CSS selector engine.
Try:
ul > li {
color:green;
}
DEMO
Since .doc-view is on the div, you need to use the negation on the div and then access the li.
So the pure CSS solution is:
ul > li {
color: red;
}
div:not(.doc-view) > ul > li {
color:green;
}
See working jsFiddle demo