Remove one of the same phrases [duplicate] - javascript

what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements
<div class="fruit">
grapes
</div>
<div class="fruit">
bananas
</div>
<div class="fruit">
grapes
</div>
I've tried using something like
$('.fruit').each(function () {
$('.fruit:has("' + $(this).text() + '"):gt(0)').remove();
});

Try
var obj = {};
$('.fruit').each(function(){
var text = $.trim($(this).text());
if(obj[text]){
$(this).remove();
} else {
obj[text] = true;
}
})
Demo: Fiddle

:has expects an element selector while :contains takes a string
see http://api.jquery.com/contains-selector/
so this should do the trick:
$('.fruit').each(function () {
$('.fruit:contains("' + $(this).text() + '"):gt(0)').remove();
});
fiddle: http://jsfiddle.net/kam7E/

http://jsfiddle.net/S3wXM/1/
Assuming that you wish to remove only one of the duplicates.
Using contains, like the answer above but implementation is slightly different.
$($("div:contains('grapes')")[0]).remove();
http://api.jquery.com/jQuery.unique/ - This also might be of use to you.

var uniqueFruits = [];
$(".fruit").each(function(i,e){
var thisFruit = $.trim($(e).text());
if(uniqueFruits.indexOf(thisFruit) == -1)
uniqueFruits.push(thisFruit);
else
$(e).remove();
});
http://jsfiddle.net/a7E9e/

jsFiddle here: http://jsfiddle.net/THEtheChad/UKRwf/
var found = {};
var $unique_fruits = $('.fruit').filter(function(){
var data = this.innerHTML.trim();
if(!found.hasOwnProperty(data)) return found[data] = true;
});

Here is the working fiddle for this:-
http://jsfiddle.net/HwUUs/1/
$( "div:contains('grapes')" ).remove();

Related

How do I search nested divs using regex for class names

I want to search for nested divs like these in my DOM
<div class="two-columns some-other-class">
<div class="two-columns some-other-class">
</div>
</div>
I tried to search nested divs like this
$("div[class$='columns'] div[class$='columns']")
but it's not working :(
Use the Attribute Contains Selector:
$("div[class*='columns'] div[class*='columns']")
Edit:
If you want that exact functionality you might want to extend the jQuery selector engine:
$.extend($.expr[':'], {
classEndsWith: function(e, i, meta) {
var found = false
var classes = e.className.toLowerCase().split(' ');
var suffix = meta[3].toLowerCase();
$.each(classes, function(i, c) {
// Check if className ends with value in suffix
if (c.indexOf(suffix, c.length - suffix.length) !== -1) {
found = true;
return false;
}
});
return found;
}
});
var element = $('div:classEndsWith(columns) div:classEndsWith(columns)');
See JSFiddle.
$("div[class$='columns'] div[class$='columns']")
Is working. Check the fiddle

Get HTML without sub-children [duplicate]

This question already has answers here:
getting the first line of text in an element jquery
(5 answers)
Closed 8 years ago.
So, I have a piece of HTML code that looks something like this:
<span class="name">SOMEUSERNAME<span class="meta">20 friends</span></span>
With a simple $(".name") I can easily the insides, but is there a way to get just the username without the meta data? I know I could use RegEx, but I'd rather know if it can be done with jQuery selectors directly, since I'm still somewhat new to that thing.
Seems like something that would be easier without jQuery
document.querySelectorAll('.name')[0].firstChild.nodeValue
FIDDLE
for more elements you can do
var users = Array.prototype.slice.call(document.querySelectorAll('.name')).map(function(el) {
return el.firstChild.nodeValue;
});
FIDDLE
or for older browsers
var elems = document.querySelectorAll('.name');
users = [];
for (var i=elems.length; i--;) {
users.push(elems[i].firstChild.nodeValue);
}
FIDDLE
or more jQuery'ish
var users = $.map($('.name'), function(el) {
return el.firstChild.nodeValue;
});
FIDDLE
Try this:
var name = $('#name').clone();
name.find('.meta').remove();
console.log(name);
Hope this helps.
Try this, if you just want the username (without the 20 friends stuff)
$(".name").clone().children().remove().end().text();
http://jsfiddle.net/9GEfY/
.contents() will return all children, including text nodes. You can do something like this:
http://jsfiddle.net/MnCDb/
$(".name").contents().get(0).textContent;
Why don't you try like this?
<span class="name" id="name">SOMEUSERNAME
<span class="meta" id="meta">20 friends</span>
</span>
<button onClick="foo()">click me </button>
<div id='result'></div>
<script>
function foo(){
var names=document.getElementById('name').innerHtml;
document.getElementById('result').innerHtml=names;
}
</script>
$('span').filter(function(){return this.className=='name'}).get(0).firstChild;
jsFiddle example
Not sure this is the most efficient approach, but this should work:
$('.name').clone().children().remove().end().text();
Edit: here's a more efficient solution:
var text = $.map($('.name').contents(), function(node) {
return node.nodeType === 3 ? node.nodeValue : '';
}).join('');
Edit: just for fun, here's a potentially "more idiomatic" jQuery approach:
var text = $($('.name').contents()).filter(function() {
return this.nodeType === 3;
}).map(function() {
return this.nodeValue;
}).get().join('')

A one-liner for finding the index of an element that has certain class within a jQuery set of elements?

I've got an arbitrary structure like this:
<h2>Foo</h2>
<p>Foo foo</p>
<p>Foofoo</p>
<h2>Bar</h2>
<h2 class=highlighted>Baz</h2>
<p>Baz</p>
<h2>Quux</h2>
<p>Quux quux</p>
In my JS i already have all h2 elements in a jQuery object:
var $headings = $('h2');
Now i need to find which of those headings has the highlighted class.
So for the above structure the third heading is highlighted, so i expect to receive the answer 2 (JS counts from zero).
I've managed to solve this task with:
function foo($jQueryObject) {
var number;
$jQueryObject.each( function(index, element) {
if ($(element).hasClass('highlighted')) {
number = index;
return false;
}
});
return number;
}
Demo: http://jsbin.com/acaGeJi/1/
But i'm sure there's a more elegant way, something like $headings.index('.highlighted');. Can you please suggest it?
You can use the map method to get the index:
var index = $jQueryObject.map(function(i, e){
return e.hasClass('highlighted') ? i : null;
})[0];
You can also use the index method, but then you have to get the element to look for first, so that means that you look for it twice:
var index = $jQueryObject.index($jQueryObject.filter('.highlighted'));
You can use the $.index function
var search = $( ".highlighted" );
alert( "Index: " + $( "h2" ).index( search ) );
This works for me:
$('.highlighted').index('h2');
jsfiddle demo

get value of inside a tag with jQuery.?

How can by jQuery get value inside tag b?
<span>
<b>hi_1</b>
<b>hi_2</b>
<b>hi_3</b>
<b>hi_4</b>
<span>
I want this output with jQuery: hi_1, hi_2, hi_3, hi_4
Please give me example in jsfiddle.
Are you looking for something like this?
http://jsfiddle.net/ZDYnq/
$(document).ready(function() {
var textArr = [];
$('span b').each(function() {
textArr.push($(this).text());
});
alert(textArr.join(', '));
});
To get the value inside a specific HTML tag in jQuery you can use the text function. This combined with a selector gets the output you're looking for
$('span b').each(function() {
console.log($(this).text());
});
JSFiddle
JSFiddle with commas
This is cool
var x = $("span b").map(function() {
return $(this).text();
}).toArray().join(", ");
Demo here
Discussed here

Give the classes a specific id

I have a question about the class, and give the class a specific id.
For example I've got a html code like this:
<div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
My question is how can I add an id by each .test class.
I thought something like this in Jquery:
var i = 1;
$('.test').each(function(){
$('.test').attr('id','id_'+i+'');
i++
});
This doesn't work I think it's something with .closest() or .next()
to solve this problem.
Regards,
Frank
EDIT:
I solved the problem by myself the answer is:
$('.test').each(function(){
$(this).attr('class','test').attr('id','id_'+i+'');
i++;
});
No reason to make a counter, .each() comes with one built in.
$('.test').each(function(i){
$(this).attr('id','id_'+i+'');
});
Use $(this) to refer to the current element the in callback function:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i);
i++
});
Much faster and simpler like this:
$('.test').each(function(i){
this.id = 'id_' + i;
});
There's no need for .attr() when setting or getting the id of an element.
Or if you wanted the numbers to start with 1, do this:
$('.test').each(function(i){
this.id = 'id_' + (i + 1);
});
You were on the right path:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i+'');
i++
});
Use this jQuery instead:
var i, $test = $('.test'), tl = $test.length;
for (i = 0; i < tl; i++) {
$test.eq(i).attr('id','id_'+i+'');
}
As i is incremented in the for loop, you select the specific element you want to give the i based id with .eq(i).

Categories

Resources