How to use DOM insertion/edit functions using jquery selectors? [duplicate] - javascript

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>

Related

how to jquery $("#elementid span")[1].html() [duplicate]

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(...);

jQuery: How to check if an element exists and change css property

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

How to apply style to a specific element in JQuery array

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(...);

Using javascript, how to select an li relative to a specific other li

Given the following html list:
<ul>
...
<li>
<li> // <-- item to be selected
<li>
<li class='current'>
<li>
<li>
<li>
...
</ul>
How do I select the li two instances ahead of the li with class current?
Any pure javascript or jquery solution would be great!
Making it more generic, i.e if you want to select a li possibly(2nd or 3rd or what ever instance that appears prior to your selector), then try
$('li.current').prevAll(':eq(' + n-1 + ')');
Here n would be the instance # that you are talking about (Since it is 0 based index). In your case this would be:
$('li.current').prevAll(':eq(1)');
Do remember that prevAll returns the elements in the order starting from the selector, so you can just provide the index of the element from that position in prevAll with eq selector.
Fiddle
Very easily:
$('.current').prev().prev()
You can try
$('.current').prev().prev()
This may help...
var li=document.getElementsByTagName('li');
var i, n;
for(i=0;i<li.length;i++)
{
if(li[i].className=='current')
{
n=(i+2)%(li.length);
}
}
var x=li[n];
I have accepted an answer. My own solution first identified the index of the element to be selected:
var index = $('.current').index()-n+1;
n equals the number of items you want to be ahead of the current object. The +1 is because indexing starts at zero, yet nth-child at 1.
I then used the nth-child selector to get the right element:
$('ul li:nth-child('+index+')')

Child selector using `querySelectorAll` on a DOM collection

Let's presume you got a list with nested child lists.
<ul>
<li></li>
<li>
<ul>
<li></li>
<li></li>
</ul>
</li>
<li></li>
</ul>
And use document.querySelectorAll() to make a selection:
var ul = document.querySelectorAll("ul");
How can i use the ul collection to get the direct child elements?
ul.querySelectorAll("> li");
// Gives 'Error: An invalid or illegal string was specified'
Let's presume ul is cached somehow (otherwise i could have done ul > li directly).
In jQuery this works:
$("ul").find("> li");
But it doesn't in native querySelectorAll. Any solutions?
The correct way to write a selector that is "rooted" to the current element is to use :scope.
ul.querySelectorAll(":scope > li");
See my answer here for an explanation and a robust, cross-browser solution: https://stackoverflow.com/a/21126966/1170723
Because the ul returned is a NodeList, it doesn't implicitly loop over its contents like a jQuery collection. You'd need to use ul[0].querySelectorAll() or better still select the ul with querySelector().
Besides that, querySelectorAll() won't take a > and work from its current context. However, you can get it to work using lazd's answer (though check the browser compatibility), or any of these workarounds (which should have no browser issues)...
[].filter.call(ul.querySelectorAll("li"), function(element){
return element.parentNode == ul;
});
jsFiddle.
This will select all li elements that are descendants of your ul, and then remove the ones which are not direct descendants.
Alternatively, you could get all childNodes and then filter them...
[].filter.call(ul.childNodes, function(node) {
return node.nodeType == 1 && node.tagName.toLowerCase() == 'li';
});
jsFiddle.
You need to iterate over the NodeList returned by document.querySelectorAll() and then call element.querySelectorAll() for each element in that list.

Categories