jQuery.each() class example Appending Div Text to Li - javascript

$EACH DEMO
anyhow iam getting the text of "div class": and printing in console.,
and iam trying to append the same text in "li > button", which is not happening, not sure where iam going wrong,
html :
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
JS:
//step - 1
$.each($('.productDescription'), function() {
var classTxt = $(this).text();
console.log(classTxt);
});
//outputs: Red Orange Green
//step - 2 now im trying to append the text to li
var liBtn = $(this).find('li').next('button');
console.log("Text of Button - "+ classTxt);
console.log(liBtn)
for (var i = liBtn.length; i >= 0; i++) {
liBtn[i]
};
Appreciate Your Help, Thanks

There are several errors in your code. classTxt is undefined outside of the each handler's context and the second this refers to window object and not to the .productDescription elements.
I'd suggest using the .append() method's callback function:
// cache the collection for better performance
var $p = $('.productDescription');
$('li button').append(function (index) {
return $p.eq(index).text();
});
http://jsfiddle.net/46yo7etz/
You could also use the .text() method:
$('li button').text(function(index, currentTextContent) {
// using indices for selecting
// the corresponding `.productDescription` element
return currentTextContent + $p.eq(index).text();
});
Please note that your fiddle's markup is invalid. li element should be child of an ul/ol element.

$('li > button').text(function() {
return $('.productDescription').eq( $('li > button').index( this ) ).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>

$("button").each(function(i){
$(this).text( $(".productDescription").eq(i).text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
http://jsfiddle.net/simply_simpy/uqmpvb7e/

Related

Modify the contents of child divs inside another div using JavaScript/JQuery

<div id="abc">
<div id="a_b"> abcd </div>
<div id="c_d"> xyz </div>
</div>
Problem is the divs are dynamically generated and their IDs keep changing every time the page is rendered. On window load, the contents of a_b and c_d has to be passed a function func() and the output should be placed within the same div. How can I grab each child of div abc and modify their contents?
Try to use .text() along with .each() to achieve what you want.
$(window).load(function(){
$("#abc > div").each(function() {
$(this).text(someFunction($(this).text()));
});
});
Or the better code would be using the receiver function of .text(),
$(window).load(function(){
$("#abc > div").text(function(_,v) {
return someFunc(v);
});
});
Given that the #abc div is always available, you can select that and then any direct child div element and loop over them by using text() with a handler function, like this:
$('#abc > div').text(function(i, v) {
return v + ' foobar';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc">
<div id="a_b">abcd</div>
<div id="c_d">xyz</div>
</div>
Alternatively you can create an array of the content of the child divs and pass that to your func():
var textContents = $('#abc > div').map(function() {
return $(this).text();
}).get();
func(textContents);
function func(arrText) {
console.log(arrText); // = [ 'abcd', 'xyz' ]
}

HTML / JS - li extra data field

I am currently trying to create a hidden field in a current list (li) in which I can pass another field other than just the text value.
Here is what I have so far:
HTML:
<ul id = "playlist" class="mejs-list" style="background: #00BFFF;list-style: none; padding: 0;list-style-type: none;width: 300px; height: 300px;overflow: auto" >
<li data-leaves="47" class="current">Test</li>
<li data-leaves="47">Test2</li>
</ul>
Javascript (I simplified the code):
$(".mejs-list li").click(function() {
var audio_src = $(this).text();
alert(audio_src)
var test = $(this).dataset.leaves
alert(test )
});
I get a display for "audio_src" no problem since this is simply the "text" of the item however I can not get the custom field to pass through.
Any ideas?
jQuery objects have no dataset proprty. Don't "cast" this to a jQuery Object:
$(".mejs-list li").click(function () {
var audio_src = $(this).text();
alert(audio_src);
var test = this.dataset.leaves;
alert(test);
});
Demo
Also learn how to use console.log for debugging. You can get alot more info that way, you can log and inspect objects to the console.
I think you should use $(this).attr("dataset-leaves") instead of $(this).dataset.leaves.
BTW, it is best practise to end each statement with a semi-comma.
Correction: should be $(this).attr("data-leaves")
use jQuery data() to return the value of data-leaves.
$('.mejs-list li').click(function() {
var audio_src = $(this).text(),
test = $(this).data('leaves');
alert('audio source: '+ audio_src + '\n data-laves: '+ test);
});
Demo: http://jsfiddle.net/pWuh9/

find index of div using jquery

here is my html code:
<div class="more-content">
<input type="text" />
<div class="post">post 1</div>
<div class="post">post 2</div>
<div class="post">post 3</div>
</div>
Here is jquery:
$(".post").click(function () {
var index = $(this).index();
alert(index);
});
i don't want to consider the input text while trying to get index of div inside of main div.Hence clicking on post 3 must show 2 and not 3.How to do that??
here is the jsfidle http://jsfiddle.net/NDySY/16/
You can use index() this way:
$(".post").click(function() {
var index = $(this).index('.post');
alert(index);
});
Fiddle
You can use: $('.post').index(this)
check: http://jsfiddle.net/NDySY/18/
Working Demo http://jsfiddle.net/cse_tushar/NDySY/21/
div.post means only div with class post
$("div.post").click(function() {
var index = $(this).index('div.post');
alert(index);
});
in class post click event fetch index as follow:
var index=$('.post').index(this);
You will have to get the number of post then subtract it by the index. You index function should also have a parameter for the selector where it should be relative to
$(".post").click(function() {
var index = $(this).index('.post');
var comp = $('.post').length - index;
alert(comp);
});
http://jsfiddle.net/NDySY/24/
You can do something like this.
$(".post").click(function() {
var eventCreator=this;
$('.post').each(function(index,value){
var currentDiv=value;
if(eventCreator==currentDiv)
{
alert(index);
//Do what ever you want to do with index
}
});
});
Check the JS Fiddle HERE

Collapse HTML if no content found

I want to be able to remove HTML elements if they contain no content.
Let's say we have some markup and are targeting all 'collapse' classes:
<div class='collapse'>[CONTENT?]</div>
If there is some content then don't do anything.
But if there is no content - no string characters or whitespace - then remove the div element completely.
This is easy to implement in the simple cases but with nested content it's slightly more more tricky.
Here is a demo, if you try removing the [CONTENTX?] strings and then seeing what the HTML structure is you'll notice that it doesn't work completely.
If a div only has other divs with no content then that should be treated as no characters or whitespace.
If we remove all [CONTENTX?] strings then we should see no HTML structure.
What ways are there to handle this?
jsFiddle: http://jsfiddle.net/97udq/
HTML:
<div id='container'>
<div class='collapse'>
[CONTENT1?]
</div>
<div class='collapse'>
[CONTENT2?]
<div class='collapse'>
[CONTENT3?]
<div class='collapse'>[CONTENT4?]</div>
<div class='collapse'>[CONTENT5?]</div>
</div>
</div>
</div>
Javascript:
$(function(){
// function
collapse();
// Show HTML structure
alert($('#container').html());
});
function collapse(){
// Loop thru all collapse elements
$('.collapse').each(function(){
// Check for pure whitespace
if($(this).html().replace(/\s+/g, '').length==0){
// Nothing to see, so remove.
$(this).remove();
}
});
}
CSS:
.collapse{
height:20px;
border:1px solid red;
}
I think this does the job;
It just uses text() instead of html();
Here's the documentation.
This one adds the trim(), but I thik that's not what you want.
function collapse(){
$('.collapse').each(function(){
if($(this).text().length==0){
$(this).remove();
}
});
}
Here's another way of accomplishing what you want. It recurses down the DOM pruning nodes from the bottom up. Hope this helps.
function prune(root) {
$.each($(root).children(), function(){
prune($(this));
});
if($(root).html().replace(/\s+/g, '').length==0 && $(root).hasClass("collapse")){
$(root).detach();
}
}
Code integrated into your JSFiddle
You need to recreate the .each() loop, but reversed. Just like that :
function collapse(){
var el = $('.collapse');
for(var i = el.length - 1; i >= 0; i--){
if(el[i].innerHTML.replace(/\s+/g, '').length==0){
$(el[i]).remove();
}
}
}
It will remove the childrens first, then check for parent.
Here a fiddle : http://jsfiddle.net/97udq/5/
EDIT :
I missunderstood your question, here's the right solution :
function collapse(){
$('.collapse').each(function(){
var $this = $(this)
var clone = $this.clone();
clone.children().remove();
if(clone.html().replace(/\s+/g, '').length==0){
$this.children().appendTo($this.parent());
$this.remove()
}
})
}
Basicly, you clone the current div, remove its children and then check if there is some text. If there's none, you append his children to his parent
Fiddle : http://jsfiddle.net/97udq/9/

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

Categories

Resources