jQuery equivalent for getElementsByClassName('name')[n]? - javascript

Is there any jQuery equivalent similar to
$(document).ready(function(){
$('para')[2].css("color","red");
});
for the code below
document.getElementsByClassName('para')[2].style.color = "red";
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
<p class="para">Content</p>
I want the CSS to be applied to the nth paragraph.

Try .eq if you want to access a specific jQuery element from a list of matched stuff:
$(".para").eq(2).css("color","red");
Edit: The dot notation, .para, is functionally equivalent to getElementsByClassName("para")

A jQuery alternative could be crafted as follows. Note that nth-of-type is not zero index based
$('p.para:nth-of-type(3)').css('color', 'red')
JSFiddle Link

You can use n-th child to set the style accordingly
$(document).ready(function(){
$( ".para:nth-child(2)" ).css("color","red");
});

I would normally use the :eq() selector for this:
$('.para:eq(2)').css('color', 'red');

Related

How to get each value of same class name?

I have some tag with same class , i want get each their value and append it to a div how to do it
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
for (i=1;i<$(".adr").length;i++) {
$("#test").append($(".adr").html() + "</br>");
}
the result :
location1
location1
location1
location1
it seems did apppend 4 times first class, how to get 1 and 2 and 3 and 4 ?
Use each in jquery to get text of all adr class . Do not append line by line as it takes more execution time.Try to append as a whole, Hope this helps
var str=''
$('.adr').each(function(e){
str+=$(this).text()+ "<br>"
})
$("#test").html(str)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id =test></div>
$('#test').append($('.adr').clone());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test"></div>
You can append all matched elements with .adr using append(). But only this would technically add the original elements and strip from it where it was previously situated in the DOM. So, clone() them to create a new copy of all elements and preserve it's previous state as well.
var rows = $(".adr");
for (var i = 0; i < rows.length; i++) {
$("#test").append($(rows[i]).html() + "<br>")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id =test></div>
$('.something') returns an array, so you need $('.something')[i] to get each item from the array.
You're calling three jQuery functions for every iteration of the loop - inefficient. Call them once each before the loop, assigning them to a variable, then use the variable instead of the jQuery calls.
You can use each() method. Secondly selecting "#test" and ".adr" is a bad idea declare them as global variable and use them.
let elms = $(".adr");
let test = $('#test');
elms.each(function(){
test.append($(this).html() + "<br>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test">
</div>
Using querySelectorAll() and map()
document.querySelector('#test').innerHTML = [...document.querySelectorAll('.adr')].map(x => x.innerHTML).join("<br>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="adr">location1</p>
<p class="adr">location2</p>
<p class="adr">location3</p>
<p class="adr">location4</p>
<div id="test">
</div>

Delete text between two tags with jQuery

Hello there fellow developers, I am trying to delete a certain character between two tags using jQuery:
<div class="product-details">
<p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p>
<strong>1</strong> x
<span class="price">9,14 €</span>
</div>
In this case the "x" between the strong and the span tag. I can't search for "x" in the product-details class because there could be an "x" in the name of the product. Thats why I thought it would be the best thing to say that everything between the <strong> and <span> should be deleted.
Also this must be done using jQuery, I have no access to this code to delete it myself. Hope anybody has a solution for me since nothing worked for me so far.
Given the example you can simply remove all child textNodes from the .product-details div. You can do that in jQuery by using contents(), filter() then remove():
$('.product-details').contents().filter(function() {
return this.nodeType == 3 && this.nodeValue.trim();
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-details">
<p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p>
<strong>1</strong>
x
<span class="price">9,14 €</span>
</div>
Alternatively, You can get target the node element using DOM relationship. Here in example, You can get a reference to <strong> node then get desired element using nextSibling
var element = document.querySelector('.product-details > strong');
//element.nextSibling.nodeValue = "Modified Value";
element.nextSibling.parentNode.removeChild(element.nextSibling)
<div class="product-details">
<p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p>
<strong>1</strong> x
<span class="price">9,14 €</span>
</div>
Use $('.product-details').children() to get the elements with the tag. Since, x do not have any tag this will be removed. Then, set this result as the new html content of .product-details.
$('.product-details').html($('.product-details').children());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-details">
<p class="product-name">Gastronormbehälter PROFI GN 1/6 - 150</p>
<strong>1</strong>
x
<span class="price">9,14 €</span>
</div>

How to select prev no to related element jquery

I would like to slide divs, all of them will have same id because they'll generate inside loop so also trigger has same id. That's why I want to use one function, at the moment function works only for first div and I have no idea how to fix it. I would like that each button would work for div above him.
html part
<div id='slide'>
hello
</div>
<p id='but'>click</p>
<div id='slide'>
hello
</div>
<p id='but'>click</p>
and the js
$(document).ready(function(){
$(this).click(function(){
$("#slide").slideToggle("slow");
});
});
First of all, don't have same ids on one page - use classes instead. If you want to do something with the element before clicked item, you can use prev(), something like this (in your code just change css('color', 'red') to slideToggle("slow"), I have added it just for example):
$(document).ready(function() {
$(".but").click(function() {
$(this).prev().css('color', 'red');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='slide'>
hello
</div>
<p class='but'>click</p>
<div class='slide'>
hello
</div>
<p class='but'>click</p>
Few issues:
Use classes not IDs and use the ID of the click element #but instead of this for your click function
<div class='slide'>
hello
</div>
<p class='but'>click</p>
<div class='slide'>
hello
</div>
<p class='but'>click</p>
$(document).ready(function(){
$('.but).click(function(){
$(".slide").slideToggle("slow");
});
});

If a div contains a specific string of text, edit the parent's css

I'd love some help with a simple jQuery script that searches for a specific string of text. If that text exists, then manipulate the containing div's css. The HTML would look like:
<div class="container">
<div>
<div class="heading">
Very important text
</div>
</div>
</div>
<div class="container">
<div>
<div class="heading">
Not important at all
</div>
</div>
</div>
<div class="container">
<div>
<div class="heading">
Very important text
</div>
</div>
</div>
<div class="container">
<div>
<div class="heading">
Not important at all
</div>
</div>
</div>
For example: If a container contains the string "Very important text" I would like to give the 'heading' class a height of 200px and its 'container' div a background of green. Please let me know if this is unclear. Thanks in advance!
CHeers.
use :contains selector in Jquery .
$(".container .heading a:contains('Very important text')").each(function(i , v){
$(this).closest(".heading").css("height" , "200px");
$(this).closest(".container").css("background-color" , "green");
});
or simply
$(".container .heading a:contains('Very important text')")
.closest(".heading").css("height" , "200px")
.closest(".container").css("background-color" , "green");
Fiddle
You can do this:
$('.container').filter(':contains("Very important text")')
.css('background-color', 'green')
.find('.heading').css('height', '200px');
Demo:http://jsfiddle.net/AmitJoki/y82X9/1
As Zword suggested, use filter. This solution is the fastest. JSPerf
just use this ..
$(".container div:contains('Very important text')").parent().css("height","300");
you can play around .
Using filter is a faster and better option:
$(".container .heading a").filter(":contains('Very important text')").closest(".heading").css("height","200px").closest(".container").css("background-color", "green");
Demo Fiddle
See test : http://jsperf.com/so-22877172

How to rearrange elements using jQuery?

How to rearrange elements using jQuery ?
Orginal Code :
<p id="paragraph1">1</p>
<p id="paragraph2">2</p>
<p id="paragraph3">3</p>
<p id="paragraph4">4</p>
<p id="paragraph5">5</p>
After Rearrange (put p3 in p2's place)
<p id="paragraph1">1</p>
<p id="paragraph3">3</p>
<p id="paragraph2">2</p>
<p id="paragraph4">4</p>
<p id="paragraph5">5</p>
You can use .insertBefore():
$("#paragraph3").insertBefore("#paragraph2");
Slightly more elaborate example (clicking on a paragraph moves it up):
$("p").click(function() {
$(this).insertBefore($(this).prev());
});
You can test both examples here.

Categories

Resources