Add class name for generated Html using jquery - javascript

Below is html part
<li class="main_menu catagory_li" id="cat4">
<p class="ahead"><span class="heading">Item 4</span>
<span class="fright remove">close</span></p>
</li>
when i click close i copy the LI using below code,
$('.remove').live('click',function(){
var closed_elem_id = $(this).parent().parent().attr('id');
s = $(this).parent().parent().clone().wrap('<div>').parent().html();
$('li#'+closed_elem_id).remove();
console.log(s);
});
This one removes the LI in particular place and get the copy and store it in variable s.
My requirement is to add class called no-display in cloned copy like <span class="fright remove no-display">close</span> . I tried this many ways but it fails.
Kindly advice on this
NOTE : updated my question

A little optimized: http://jsfiddle.net/hKUd6/

Something like this:
$('.remove').live('click',function(){
var pLi = $(this).closest('li');
s = $('<div>').append(pLi.clone().addClass('no-display')).html();
pLi.remove();
console.log(s);
});

This whole thing is very sloppy. You don't need to use as much code as you have to accomplish the simple task you're attempting.
Try something like this:
$("li").on("click", ".remove", function(){
var $this = $(this),
liCont = $this.closest("p"),
parentLi = $this.closest("li");
liCont
.clone()
.wrap(
$("<div>").addClass("no-display")
)
.appendTo("body");
parentLi.remove();
});
What we do here is capture the click event on any .remove elements. We select the parent p (which we later clone to wrap with a div) as well as the parent li. We clone the p element (including its contents), wrap it with a div element (which we create using DOM scripting and add the class), and append the finished product to the body (you can change that if needed). We then remove the original li.

Try with this code, it should work:
$('.remove').live('click',function(){
var closed_elem = $(this).closest("li"); //get the li to be closed/removed
var clonedElem = closed_elem.clone().find("span.remove").addClass("no-display"); //clone the original li and add the no-display class to the span having remove class
closed_elem.remove(); //remove the original li
console.log(clonedElem);
});

Please check below lines of code.
first of all you need to get current class name using jquery:
$('li #cat4').find('span').each(function(){
var classname = $(this).attr('class');
$(this).addClass(classname+' no-display');
});
This is not a complete code of your task, but its just a code by which you can get a current class and then add more required string to it and set new class.
Thanks.

Related

Deleting a tag from a html string using Jquery

I am trying to delete a span class from a HTML string using Jquery. My HTML string looks like this:
<li class="left clearfix"><span id="userAvatar" class="chat-img pull-left"><img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle"></span><div class="chat-body clearfix"><div class="header"><strong class="primary-font">sdfsdf3424</strong></div><p>dfgfg</p></div></li>
To delete the span tag from this string I am doing the following:
var JqueryObj = $('<div/>').html(stringHTML).contents();
JqueryObj = JqueryObj.not("#userAvatar");
stringHTML = JqueryObj.html();
Where am I going wrong? Also is it possible to change the font color of the paragraph tag inside this string?
For your first question, you should just be able to do the following:
var htmlstring = '<li class="left clearfix"><span id="userAvatar" class="chat-img pull-left"><img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle"></span><div class="chat-body clearfix"><div class="header"><strong class="primary-font">sdfsdf3424</strong></div><p>dfgfg</p></div></li>'
var obj = $("div").html(htmlstring);
obj.find("#userAvatar").remove();
var newhtmlstring = obj.html();
This makes a new element that has the contents of the htmlstring in it. Then, the find part finds all direct and indirect children with the selector and removes them. finally, the new html string is the contents of the temporary object we created before.
Using .find(), you can also change the font color:
obj.find("p").css("color", "red");
here is a possible solution which explains how to remove span in a div.
var divContent = $("div").html(stringHTML);
divContent = $(divContent).find("#userAvatar").remove();
$("div").empty().html($(divContent).html());
use
$( "span" ).remove();
DEMO : http://jsfiddle.net/ryxbpn2s/2/
I am not exactly sure what you are trying to achieve so I will post a few solutions, maybe one of them will solve your problem.
1) You want to remove the a class from span#userAvatar:
You should use jQuerys removeClass function.
Usage:
$( "#userAvatar" ).removeClass( "className" )
2) You want to remove the span but keep the contents:
You can just replace the whole span with what's inside.
Usage:
$("#userAvatar").replaceWith(function() {
return $("img", this);
});
3) You want to remove the span class and everything that's inside it:
You should use jQuery's remove() function.
Usage:
$("#userAvatar").remove();
To change the colour of the paragraph you can use jQuery's find() function.
Usage:
JqueryObj.find("p").css("color", "#EEEEEE");
Hope this helps.

Selecting text within a span within a link within an unordered list... and then replacing it

Here's the HTML I'm focusing on:
<nav>
<ul id='nav'>
<li></icon>Home<span> +</span></li>
<li><icon><img src="images/skills-icon.png"></icon>Skillsets</li>
<li><icon><img src="images/gallery-icon.png"></icon>Gallery</li>
<li><icon><img src="images/about-icon.png"></icon>About</li>
<li></icon>Contact</li>
</ul>
</nav>
I want to select the text within the span—preferably only the "+" part of the text within the span (without the space). The way I'm trying to do that right now is with this code:
$(document).ready(function(){
var ul = $('nav > ul'),
li = ul.children('li'),
top = li.find('a').hasClass("top"),
navSpan = $(top).children('span');
$(navSpan).contents().replaceWith(' -');
});
but it isn't selecting the element correctly. With the way I have my javascript set up (there's a lot more of it than this) I need to keep these variables. However, it appears that some of these variables aren't set up correctly, or that my $(navSpan).contents().replaceWith() command isn't set up correctly. Do you guys have any ideas on how to fix it? Thanks!
First of all, lets fix your selectors and your double-wrapping:
$(function(){
var ul = $('#nav'),
li = ul.children('li'),
top = li.find('a.top'), // you can remove the 'a' qualifier if there is never another item with the top class
navSpan = top.children('span');
Second of all ... you can just replace the contents with this:
navSpan.text(' -');
});
Final code:
$(function(){
var ul = $('#nav'),
li = ul.children('li'),
top = li.find('a.top'),
navSpan = top.children('span');
navSpan.text(' -');
});
I cringe a little bit at the volume of unnecessary variables in this example, but you said you need all of them so I won't try to further optimize.
EDIT: Couldn't resist optimizing a little. Even if you need to capture all of those variables, you will have a faster querying with an id than you will using nav > li. If you have multiple menus that this applies to then disregard, but if not then this would be a little faster.
Here is a jsFiddle of the working code.
hasClass returns a boolean value. If you want to filter an element, you can use the filter method: li.find('a').filter(".top")
contents returns the childNodes of an element, you can't call jQuery methods on the returned value.
$('nav > ul').find('a.top span').text(' -');

Jquery appending without removing

So I need to grab content from a specific class and put it in a div, which I use append for...my issue is that append removes the item I append, and I need it to stay there, Here is my code:
$(document).ready(function(){
var $content = $('#popupcontent');
var $window = $('#popupwindow');
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a);
$window.fadeIn(300);
});
$('.close').click(function(){
//alert('running');
var a = $content.contents('span');
$window.fadeOut(300);
$('#popupcontent span').remove();
});
});
So how can I get the content, when clicked, from each .open span to the #popupcontents id without removing it from the .open class?
To show you what I mean: JSFIDDLE
NOTE: the second time you click a link, it wont append any content because that content has been removed from that class, which is not what I want
NOTE2: I cannot simply just append instead of remove in the $('.close').click function because I cannot detect which instance of the .open class the content came from.
You need to clone the element and append the clone:
$('.open').click(function(){
//alert('runnning');
var a = $(this).contents('span');
$content.append(a.clone());
$window.fadeIn(300);
});
Demo

Inserting variable into array item

I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/

jQuery addClass() to element generated after append()

I am trying to add a class to a newly appended DIV without using something like:
t.y.append('<div class="lol'+i+'"></div>');
Here's a better example of what I'm trying to do:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append('<div></div>').addClass('lol'+i);
});
Page load HTML looks like:
<div class=".slideButton0 .slideButton1 .slideButton2" id="sliderNav">
<div></div>
<div></div>
<div></div>
</div>
When you append an element through .append, it doesn't change the context of the jQuery object.
You could write it like this:
$('<div></div>').appendTo(t.y).addClass('lol'+i);
or
$('<div></div>').addClass('lol'+i).appendTo(t.y);
(these both do the same thing, simply in different orders, the second possibly being more clear)
the context of the jQuery object will be the newly created div.
t.y.append('<div></div>').addClass('lol'+i);
should be
t.y.append('<div></div>').find('div').addClass('lol'+i);
In the first case you are adding class to the div to which you are appending ..
SO the context is still the parent div and not the newly appended div..
You need to find it first inside the parent and then add the class..
EDIT
If you want to just add the class to the last appended element ... Find the last div in the parent and then add the class to it..
This will make sure you are not adding the class to all the div's every single time you iterate in the loop..
t.y.append('<div></div>').find('div:last').addClass('lol'+i);
Try this:
t.y.append($('<div></div>').addClass('lol'+i));
Fiddle: http://jsfiddle.net/gromer/QkTdq/
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
var d = $('<div />').addClass('lol' + i);
t.y.append(d);
});
The problem is that append returns the container instead of the thing you just appended to it. I would just do the addClass before the append instead of after:
var t = this;
$(this.x).each(function(i, obj) {
//append new div and add class too <div></div>
t.y.append($('<div></div>').addClass('lol'+i));
});
EDIT ... or, in other words, exactly what Gromer said. Beat me by five whole minutes, too. I'm getting slow.
You don't mention why you want to number the class attribute to your list items, but in the case that you are actually using them for css don't forget you have :odd and :even css selector attritbutes and also the equivalent odd/even jQuery selectors.
http://www.w3.org/Style/Examples/007/evenodd.en.html
http://api.jquery.com/odd-selector/
I didn't find anything like this. notice the class attribute!
$.each(obj, function (_index, item) {
resultContainer.append($('<li>', {
class: "list-group-item",
value: item.id,
text: item.permitHolderName || item.permitHolderId
}));
});

Categories