I have 3 values that I need to replace within 3 divs.
<div class="bx-pager-item">
<a class="bx-pager-link active" data-slide-index="0" href="">1</a>
</div>
<div class="bx-pager-item">
<a class="bx-pager-link" data-slide-index="1" href="">2</a>
</div>
<div class="bx-pager-item">
<a class="bx-pager-link" data-slide-index="2" href="">3</a>
</div>
I need to replace 1, with the value 'test'; 2 with the value 'test1'; and 3 with the value 'test2'.
I have tried the following code without any success, any help would be appreciated.:
$(document).ready(function() {
var fandreplace = document.getElementsByClassName('bx-pager-item').innerHTML.replace('3', 'test2');
});
You should loop each element and replace their values accordingly.
Replace based on Index
$('.bx-pager-link').text(function (i, v) {
return 'test' + (i > 0): (i - 1): '';
});
Replace based on value
$('.bx-pager-link').text(function (i, v) {
var val = parseInt(v, 10);
return 'test' + (val > 0): (val - 1): '';
});
You need to individually set them since the new html will be unique (you could do a loop depending on what you really want to replace it with).
Here's a simple way to change the inner html using the "index" of each element.
fiddle
$(document).ready(function() {
$('.bx-pager-item:eq(0)').html('test');
$('.bx-pager-item:eq(1)').html('test1');
$('.bx-pager-item:eq(2)').html('test2');
});
In jquery you would do
$('.bx-pager-item > a').each(function(){
var str = $(this).text().replace('3', 'test2');
$(this).text(str);
});
and if you wanted several values
var map = {'3':'test2', '1':'test'};
$('.bx-pager-item > a').each(function(){
$(this).text(map[$(this).text()]);
});
JSFiddle: http://jsfiddle.net/rNLvU/
$('.bx-pager-item').each(function(){
var $this = $(this);
$this.text('test'+$this.text().trim());
});
note the text needs trimming in this instance as a leading space can occur in the element's text() value
Try this : use each to select all the elements
$(document).ready(function(){
$('.bx-pager-link').each(function (i, elem) {
$(elem).text('test '+i);
});
});
Related
I have the following HTML:
<div id="foo">
<span>
X
1
</span>
<span>
X
2
</span>
<span>
X
Hello
</span>
</div>
I want to use jQuery to get only the following 1, 2 and hello in JS (that means no <a> tags or ). Please note that I do not want to affect the DOM itself. I just want to retrieve the text in an object such as an array.
This is what I have so far:
$('#foo span');
However I can't seem to remove the "a" tag.
The following does not seem to work either:
$('#foo span').remove('a');
I'm also aware that .remove() affects the DOM it self, and does not just retrieve the text.
Solution creates array by looping over each child and cloning it to do manipulation so dom stays intact
var values = $('#foo').children().map(function () {
var $clone = $(this).clone();
$clone.children().remove();
return $.trim($clone.text());
}).get();
console.log(values) /// ["1","2","Hello"]
DEMO
This piece of code will get that value for you:
$('#foo span').each(function(){
console.log($.trim($(this).html().substring($(this).html().lastIndexOf(" ") + 6)));
});
Working jsFiddle:
http://jsfiddle.net/mrwqs2nb/1/
Open the console, you will see:
1
2
Hello
Since your problem is not detailed , on the basis of your requirements , this can be done as below
var res=[];
$('#foo span').map(function(i){
var htm=$(this).text();
var htm_d=$(this).find('a').html();
htm=$.trim(htm.split("").reverse().join(""));
htm_d=$.trim(htm_d.split("").reverse().join(""));
res[i] = htm.substring(0,htm_d.length);
} );
alert(res);
LIVE http://jsfiddle.net/mailmerohit5/5bvavx0p/
Not sure what the rules of this game are, but if it can be asumed that what you want is on the right of the then this should do it:
$('#foo span').map(function() {
//Split at the space.
var parts = $(this).html().split(' ');
//Remove the first element from the list.
parts.shift();
//Join and return.
return parts.join('');
}).get();
Use jquery's contents - the api page has an example on how to extra text nodes while ignoring other elements.
var result = $("#foo span")
.contents()
.filter(function() {
// #text nodes
return this.nodeType === 3;
}).map(function() {
// get the value and trim it (also removes  )
return $(this).text().trim();
}).filter(function() {
// remove blanks
return this != "";
}).toArray();
$("#result").text(result.join());
Working fiddle
Try using selector $("foo span") , $.map() , String.prototype.match() with RegExp [0-9]+|[a-z]+[^\s+|\n+|" + el.querySelector(".no-want").textContent + "]", "ig" to match digit or characters a-z case insensitive , negating space character , or newline character , or ".no-want" element .textContent at index of parent span element
var res = $.map($("#foo span"), function(el, index) {
return el.textContent.match(new RegExp("[0-9]+|[a-z]+[^\s+|\n+|"
+ el.querySelector(".no-want").textContent.trim() + "]", "ig"))
});
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">
<span>
X
1
</span>
<span>
X
2
</span>
<span>
X
Hello
</span>
</div>
Try using RegEx to match what you want
$('#foo span').each(function () {
alert($(this).html().match(/[0-9]/));
});
JSFIDDLE
I have an HTML structure like this:
<div id="tip1">
<div class="tip-icon"></div>
</div>
<div id="tip2">
<div class="tip-icon"></div>
</div>
<div id="tip3">
<div class="tip-icon"></div>
</div>
<div class="1 content"></div>
<div class="2 content"></div>
<div class="3 content"></div>
And I have a jQuery function like this:
$('.tip-icon').mouseenter(function() {
$('.1').addClass('tip-show'); //Change .1 to a variable
});
$('.tip-icon').mouseleave(function() {
$('.1').removeClass('tip-show2'); //Change .1 to a variable
});
But instead of having $('.1'), I want it to be the class numbers 1-3 depending on which "tip-icon" was hovered. I need to make is so that on "tip-icon" mouseenter it will take the parent div's id and delete the first 3 letters so that it is just the number left and store it into a variable. I then want to take this variable and use it in $('???').addClass('tip-show'); so that the ??? are replaced by the variable to make it so that one of divs with the classes 1-3 will get the 'tip-show' class added depending on which 'tip-icon' was hovered.
https://jsfiddle.net/oak4L9ga/
Dont do all that string mashing just to get the id out of the class. Instead tie your elements/functionality together using data-* attributes
<div id="tip1" data-tipid="1">
<div class="tip-icon"></div>
</div>
Then you can use that within your code to get the right id (actually, in your case class name)
$('.tip-icon').mouseenter(function () {
var tipId = $(this).parent().data('tipid');
$('.' + tipId).addClass('tip-show'); //Change .1 to a variable
});
Live example: https://jsfiddle.net/oak4L9ga/6/
You don't need to hack around the string of the class attribute as you can simply use index() to retrieve a numerical value representing the position of an element within a selector. Try this:
$('.tip-icon').on({
mouseenter: function () {
$('.' + ($(this).index('.tip-icon') + 1)).addClass('tip-show');
},
mouseleave: function () {
$('.' + ($(this).index('.tip-icon') + 1)).removeClass('tip-show');
}
});
Example fiddle
This can then be made shorter by using hover and toggleClass:
$('.tip-icon').hover(function () {
$('.' + ($(this).index('.tip-icon') + 1)).toggleClass('tip-show');
});
Example fiddle
Just make use of html5 data attribute:
Fiddle here: https://jsfiddle.net/oak4L9ga/8/
you can use hover for this as combination of mouseenter and mouseleave. Use regex to get the number in the id of parent.
$('.tip-icon').hover(function () {
var id = $(this).parent().attr('id').replace(/[a-z]/ig, '');
// Get the number from the id
$('.' + id).addClass('tip-show').show();
}, function () {
$('.content').removeClass('tip-show').hide();
});
Demo: https://jsfiddle.net/tusharj/oak4L9ga/9/
try
$(".tip-icon").hover(
function () {
$('.' + $(this).parent().attr("id").replace('tip', '')).addClass('tip-show');
}, function () {
$('.' + $(this).parent().attr("id").replace("tip", "")).removeClass('tip-show');
});
Updated Fiddle
Like this you mean?
$('.tip-icon').mouseenter(function() {
var id = $(this).parent().attr('id').substring(3, 1);
$('#'+id).addClass('tip-show');
});
Using JQuery chaining concept.
Check JQuery:
$('.tip-icon').mouseenter(function () {
var idValue = $(this).parent('div').attr('id').substr(3, 4);
$('.'+idValue).addClass('tip-show');
});
$('.tip-icon').mouseleave(function () {
var id_Value = $(this).parent('div').attr('id').substr(3, 4);
$('.'+id_Value).removeClass('tip-show');
});
Demo:
https://jsfiddle.net/oak4L9ga/11/
How can I get the third and forth value of class="myDivs" using jQuery?
Below is my code:
HTML :
<div class="myDivs">Stack</div>
<div class="myDivs">Over</div>
<div class="myDivs">Flow</div>
<div class="myDivs">And</div>
<div class="myDivs">Exchange</div>
<div class="myDivs">Question</div>
<div class="myDivs">Ask</div>
You can use :eq to get the element at particular indexes.
Live Demo
$('.myDivs:eq(2), .myDivs:eq(3)').each(function(){
alert($(this).text());
});
Using the combination of :gt and :lt will give you range. It is useful when you have many elements.
Live Demo
$('.myDivs:gt(1):lt(2)').each(function(){
alert($(this).text());
});
Edit To make it dynamic so that you do not have to hard code the middle you can divide the length of element collection and use it for start point, this will make it work independant of how many elements you have with class myDivs.
Live Demo
mid = Math.floor($('.myDivs').length /2) -2;
$('.myDivs:gt(' + mid +'):lt(2)').each(function(){
alert($(this).text());
});
You can use .slice()
Reduce the set of matched elements to a subset specified by a range of
indices
and push the text value into an array using .map():
var valArr = $('.myDivs').slice(2,4).map(function() {
return this.textContent;
}).get();
Fiddle Demo
One dynamic way is to calculate by the length of class count.
var mid1=Math.ceil($('.myDivs').length/2) - 1,
mid2=Math.floor($('.myDivs').length/2) - 1;
if(mid1===mid2){
//handle the case
}
$('.myDivs:eq('+mid1+'), .myDivs:eq('+mid2+')').each(function(){
alert($(this).text());
});
Here is demo
Reference them by index
var myDivs = $('.myDivs'),
third = myDivs.eq(2),
fourth = myDivs.eq(3);
To get the text value, just use text()
use
$( "div:nth-child(3)" ).html();
$( "div:nth-child(4)" ).html();
it will return you text of 3 and 4 div text
Fiddel
jQuery has a simple get function
http://api.jquery.com/eq/
var $myDivs = $(".myDivs");
var nr3 = $myDivs.eq(2);
var nr4 = $myDivs.eq(3);
If you are planning to perform same operation on both the third and fourth divs, then use the following code:
$('.myDivs:eq(2), .myDivs:eq(3)').each(function(){
// perform your operation here
});
If you want to perform different tasks on both of them, then
var myDivs = $(".myDivs"),
thirdDiv = myDivs[2],
fourthDiv = myDivs[3];
Now you can bind custom events to those particular divs alone.
for example :
$(thirdDiv).click(function() {
// custom function
});
I have HTML like
<a href="/blabla" class="matchupLink">
<span class="teams"> USA</span>
<span class="teams">Brazil</span>
</a>
I want to get the HTML of the elements with class 'teams' within class 'matchupLink'
I tried
$('.matchupLink').each(function (index, obj) {
var teams = $(this).find('.teams');
console.log(teams.html())
});
But that only returns the first instance of the .teams class within each .matchupLink class. So here it only returns USA and not Brazil.
I want to calculate how many characters both teams class have within each matchupLink class. Because then if characterCount >=20, I want to display ellipses.
What should I be doing?
Thanks
You can combine selectors with the classes
$('.matchupLink .teams')
This will return you an array of objects with the class "teams".
UPDATE
Here's a fiddle that prints to the console the length
$('.matchupLink .teams').each(function(index, item){
var $item = $(item);
var teamNameLength = $item.html().length;
console.log($item.html() + ' length is: ' + $item.html().length);
// if ($item.html().length >= 20){
// ::do logic for ellipses::
// }
});
**note the USA prints out a value of 4 because you have a space before in your example.
UPDATE 2
Fiddle alerting the length of both teams
To get the length of both teams, create a variable outside of the loop and increment it appropriately.
var lengthOfBothTeams = 0;
$('.matchupLink .teams').each(function(index, item){
lengthOfBothTeams += $(item).html().length;
});
alert('Length of both team names is: ' + lengthOfBothTeams);
console.log will work on the first match in the set in your example
you should loop over the teams and not the matches
$('.matchupLink .teams').each(function () {
console.log($(this).html())
});
html() only returns the HTML content of the first matched element in the jQuery object. Use each() to iterate over the element and display their HTML content.
$('.matchupLink .teams').each(function (index, obj) {
console.log($(this).html());
});
I need to read elements class name. I have elements like this:
<article class="active clrone moreclass">Article x</article>
<article class="active clrtwo moreclass">Article y</article>
<article class="active clrthree moreclass moreclass">Article z</article>
<article class="active clrone moreclass">Article xyza</article>
I need to parse out class name that starts with clr. So if second element was clicked then I would need to get clrtwo className.
You can use a regular expression match on the class name of the clicked item to find the class that begins with "clr" like this:
$("article").click(function() {
var matches = this.className.match(/\bclr[^\s]+\b/);
if (matches) {
// matches[0] is clrone or clrtwo, etc...
}
});
Here is solution for you:
$('article').click(function () {
var className = this.className.split(' ');
for (var i = 0; i < className.length; i+=1) {
if (className[i].indexOf('clr') >= 0) {
alert(className[i]);
}
}
});
http://jsfiddle.net/vJfT7/
There's no matter how you're going to order the different classes. The code will alert you a class name only of there's 'clr' as a substring in it.
Best regards.
If you don't need to find elements based on these classes (e.g. doing $('.clrtwo')) it would be nicer to store the data as a data-clr attribute. This is standards-compliant from HTML5, and is supported by jQuery using the .data() function.
In this instance, I would modify your HTML in this way:
<article class="active moreclass" data-clr="one">Article x</article>
<article class="active moreclass" data-clr="two">Article y</article>
<article class="active moreclass moreclass" data-clr="three">Article z</article>
<article class="active moreclass" data-clr="one">Article xyza</article>
I would then use Javascript like this:
$('article.active').click(function() {
console.log($(this).data('clr'));
});
jsFiddle example
If it is always the second class name which is of interest you can do this:
$("article").click(function () {
// split on the space and output the second element
// in the resulting array
console.log($(this)[0].className.split(" ")[1]);
});
http://jsfiddle.net/karim79/Z3qhW/
<script type="text/javascript">
jQuery(document).ready(function(){
$("article").click(function(){
alert($(this).attr('class').match(/\bclr[^\s]+\b/)[0]);
});
});
</script>
This should jquery script should do what you asked (tested on jsfiddle):
$(document).ready(function () {
function getClrClass(elem) {
var classes = elem.getAttribute('class').split(' ');
var i = 0;
var cssClass = '';
for (i = 0; i < classes.length; i += 1) {
if (classes[i].indexOf('clr') === 0) {
cssClass = classes[i];
i = classes.length; //exit for loop
}
}
return cssClass;
};
$('article').click(function (e) {
var cssClass = getClrClass($(this)[0]);
alert(cssClass);
e.preventDefault();
return false;
});
});
Hope this helps.
Pete
Use an attribute selector to get those that have class names that contain clr.
From there:
extract the class name (string functions)
analyze the position
determine the next element
The latter two might be best served by a translation array if you only had a few classes.
UPDATE
I agree with lonesomeday, you'd be far better off using data-* attribute to handle such logic. Using CSS as JavaScript hooks is a thing of the past.
http://jsfiddle.net/4KwWn/
$('article[class*=clr]').click(function() {
var token = $(this).attr('class'),
position = token.indexOf('clr');
token = token.substring(position, token.indexOf(' ', position));
alert(token);
});