jQuery copy content and remove class from it before appending - javascript

I want to clone the content of the div using jQuery, but from the copied content I want to find a class active and remove it before I use appendTo function.
So for example, I have this code:
<div class="box">
<p>text</p>
<div class="random active"></div>
</div>
I can copy the above code using this:
var content = $(this).find('.box').html();
Now how can I find the class active from the var content and remove it before I can appendTo?
Please note, I do not want to remove class from actual div from where I copied the content, I just want to remove from the copied code so that it is not included in the clone div.
Thanks.

Try,
var content = $(this).find('.active').removeClass('active').closest('.box').html();
As per your new request,
var content = $(this).find('.box').clone().find('.active').removeClass('active');

My way to solve the problem:
var content = $(this).find('.box').children().clone().removeClass("active");
content is a jQuery array with the content of .box (a clone of the content) with all element without active class.
An alternative:
If you need to remove the class only from an element you can add a step:
var content = $(this).find('.box').children().clone();
content.find(".random").removeClass("active");
How can you use content variable:
Right now you can .appendTo() content where you need:
content.appendTo("body"); //for example
Debug code:
To use: alert(content.html()) try this:
var content = $(this).find('.box').clone();
content.children().removeClass("active");
alert(content.html()); //HTML string but it seems the best way to use DOM
but is better this way, using console:
var content = $(this).find('.box').children().clone().removeClass("active");
console.log(content); // array of jQuery objects not simply HTML string
An example:
example: http://jsfiddle.net/Frogmouth/4dYM4/1/
enjoy, Frog.

You can do:
$(content).find('.active').remove().appendTo('body');

Try
content = $(content).find('.active').removeClass('active')
Updated after OP's comment
Fiddle Demo
var content = $(this).find('.box').clone();
content = content.find('.active').removeClass('active').closest('.box');
alert(content.html());

You can do this.
var content = $(this).find('.box').clone();
$(content).find('.active').removeClass('active');

Best way, to remove and append element
content = $('#content').clone();
$('#content').remove();
content.appendTo('#perntElement');

Related

Inserting div into existing div with class only

I'm trying to create a new div in Javascript with two spans in it, each containing a string of text. They are then meant to be inserted before div.two in div.inner.
The div I'm trying to insert it into only has a class and I cannot target it by any ID, unfortunately.
I have also created a codepen here: https://codepen.io/lisaschumann/pen/BXqJKY
Any help is massively appreciated!
HTML
<html>
<div class="inner">
<div class="one"></div>
<div class="two"></div>
</div>
</html>
JS
window.onload=function(){
var infobox = document.createElement("div");
infobox.classList.add('infobox');
var spanOne = document.createElement("div");
var spanOneText = document.createTextNode('Important text 1');
var spanTwo = document.createElement("div");
var spanTwoText = document.createTextNode('Important text 2');
spanOne.appendChild(spanOneText);
spanTwo.appendChild(spanTwoText);
infobox.appendChild(spanOne);
infobox.appendChild(spanTwo);
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
}
Errors:
Cannot read property '1' of undefined
at window.onload
The main issue is that getElementsByClassName returns a live collection of nodes rather than one node and so you would need to access the correct node in that list similar to an array: targetDiv[0], perhaps.
The easier method is to use querySelector to grab the element you want using its class, for example:
var parent = document.querySelector(".inner");
var two = document.querySelector(".two");
parent.insertBefore(infobox, two);
But! there's even a shortcut method you can use here that allows you to add an HTML string direct to the DOM which might save you a bit of time, and some code.
// Create the HTML
const html = `
<div>
<span>Text alpha</span>
<span>Text beta</span>
</div>`;
// Grab the element containing your "two" class
const two = document.querySelector('.inner .two');
// Using insertAdjacentHTML to add the HTML before the two element
two.insertAdjacentHTML('beforebegin', html);
<div class="inner">Inner
<div class="one">one</div>
<div class="two">two</div>
</div>
insertAdjacentHTML
This doesn't work because of these lines
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
document.getElementsByClassName returns a NodeList. targetDiv.childNodes is undefined, because childNodes doesn't exist on a NodeList.
You need to either use a list operation like Array.prototype.forEach, change getElementsByClassName to getElementByClassName (note the s) or access the first node in the node list using the array indexer syntax.
I assume you meant to do something like this:
var targetDiv = document.getElementByClassName('inner')
targetDiv.insertBefore(infobox, targetDiv.childNodes[1])
This will insert a node in between the first and second child of the first DOM node with the class inner.
Try this out , targetDiv is an array by default due to the getElementsByClassName method , even though it has a single element.Hence you need to specify the index i.e. 0 ( as it's the first element of the array)
var targetDiv = document.getElementsByClassName("inner")[0]; targetDiv.insertBefore(infobox, targetDiv.children[1]); }
Using JQuery
$(document).ready(function(){
$(`<div>Important text 1<span></span>Important text 2<span></span></div>`).insertBefore( ".inner .two" );
)
I would encourage you to use JQuery and then shift to vanilla javascript later on. You can do simple tasks like this in just few lines of code and it is also easily debuggable because of that

Get element by id and put it inside bootstrap col

I have a div with an ID, this div is added to the web page by the library but i want to put this div in a col-xs-6, can i do something like document.getElementById() then put it in col-xs-6?
The easiest way to do this without any framework is to use element.classList.add method.
var element = document.getElementById("div1");
element.classList.add("otherclass");
IF your using jquery then you can simply do this,
$('#Id_of_element').addClass('col-xs-6')
If I understood you correctly you want to grab this div by id and add to it bootstrap class col-xs-6. If so then try this:
var yourDiv = document.getElementById("ID");
yourDiv.className += " col-xs-6";

Adding and finding classes that is dynamically added to body - jquery

Is there any way to add classes or alter objects that is dynamically added to the body?
I am adding a range of objects to the body by javascript.
Fot instance Im adding some links that is dynamically generated and added to the body. When they are loaded I need to elect the first of the divs and add a new class to it.
I can't seem to find any way to do this... Update the DOM or how should I go around this? There must be a way to alter dynamically added objects.
Any clues?
Thanks for any help!
if you added them dynamically, then you can just use the objects you already have. Otherwise you'll need to find them with sizzle.
//create the elements
var $link1 = $('<a>click me</a>').attr('href','page1.html');
var $link2 = $('<a>click me</a>').attr('href','page2.html');
//append the elements
$('#some-links').append($link1).append($link2);
//use the element we created
$link1.addClass('my-class');
//find the second link element using sizzle
$('#some-links>a').eq(1).addClass('my-other-class');
demo: http://jsfiddle.net/PtebM/2/
Well of course you caN:
var a = $('<a>');
a.html('new link').appendTo('#menu');
a.addClass('border');
or
var a = $('<a>');
a.html('new link').appendTo('#menu');
$('#menu a').addClass('border');
fiddle http://jsfiddle.net/4NPqH/
Why not just add a class name to your generated elements?.
I.e.:
$('span').html('Hello world').addClass("fancyText").appendTo('body');

jQuery get content between <div> tags

This'll probably be easy for someone:
var x = '<p>blah</p><div><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
How do I extract only the portion between the div tags <div>I want this</div>
Don't focus on the <a> tag as the content could be different inside the div.
This is probably what you need:
$('div').html();
demo
This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/
If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so
$('#whatever').html();
where whatever is the id
EDIT
Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:
var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);
Demo Here
get the length of the string.
find out where the first div occurs
slice the content there.
jQuery has two methods
// First. Get content as HTML
$("#my_div_id").html();
// Second. Get content as text
$("#my_div_id").text();
Give the div a class or id and do something like this:
$("#example").get().innerHTML;
That works at the DOM level.
Use the below where x is the variable which holds the markup in question.
$(x).find("div").html();
use jquery for that:
$("#divId").html()
I suggest that you give an if to the div than:
$("#my_div_id").html();
var x = '<p>blah</p><div><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
$(x).children('div').html();
Use the text method [text()] to get text in the div element,
by identifing the element by class or id.
This work for me
var content = '<p> demp text </p>';
$('#wordContent').html(content);
$('#wordContent').html($('#wordContent').text());

How to get clone of HTML, modify it, get HTML string without affecting DOM?

I have some HTML code like this:
<div style="background:red;width:900px;height:200px" id="wrap">
<div id="inner" style="width:300px;float:left">
...
</div>
</div>
I need to:
1) Remove "styles" attribute and maybe some others
2) Leave only "id" attribute
4) Get resulting HTML as a string
5) All of this without affecting the original markup
I have tried cloning them as javascript object, but manipulations on them affect DOM.
You could clone your #wrap element, modify the as you desire, and append it to a new element, that doesn't exists on the DOM:
var cloned = $('#wrap').clone(),
container = $('<div></div>');
cloned.find('div').andSelf().removeAttr('style');
alert(container.append(cloned).html());
Check the above example here.
It sounds like you had the right approach, clone-and-alter should definitely work. I don't know why your code was altering the original DOM, but this doesn't:
var el= document.getElementById('wrap');
el= el.cloneNode(true);
el.removeAttribute('style');
el.getElementsByTagName('div')[0].removeAttribute('style');
// Get full markup (like outerHTML, but better-supported)
//
var outer= document.createElement('div');
outer.appendChild(el);
alert(outer.innerHTML);

Categories

Resources