Matt Coady
Matt Coady

Reputation: 3856

jQuery append object and add string

Trying to get div 1 into div 2 and wrap brackets around the text.

Attempt

$('.div1').append('(' + $('.div2') + ')');

Before

<div class="1"></div>
<div class="2">blah</div>

What I want

<div class="1"><div class="2">(blah)</div></div>

Upvotes: 1

Views: 5693

Answers (8)

Surya Narayan
Surya Narayan

Reputation: 558

Try this

$(function(){
    $('div.2').text('('+$('div.2').text()+')');
    $('div.1').html($('div.2'));
});

Demo

Upvotes: 1

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

You should clone the element then add the parentesis to it, and append it to the other div. After that you can always remove the old element.

JS

var div2 = $('.div2').clone();
div2.text('(' + div2.text() + ')');
$('.div1').append(div2);

Html

<div class="div1"></div>
<div class="div2">blah</div>

Jsfiddle

Upvotes: 0

sSaroj
sSaroj

Reputation: 268

Hope this helps..

$('div.1').append($('div.2'));
$('div.2').html("(" + $('div.2').html() + ")");

Upvotes: 0

j08691
j08691

Reputation: 207861

$('.div1').append($('.div2').html('(' + $('.div2').html() + ')'));

jsFiddle example

Upvotes: 2

Eric Robinson
Eric Robinson

Reputation: 2095

You JS could look like this

$( document ).ready(function() {
  $('.1').append('(' + $('.2').html() + ')');
   $('.2').remove();
});

Here's a working example. http://jsfiddle.net/cVD6X/

Hopefully this is what you intended.

Regards, Eric Robinson

Upvotes: 0

codingrose
codingrose

Reputation: 15699

Try:

var html = $('.div2');
var text = $('.div2').text();
$(html).text("("+text+")");             
$('.div1').append(html);

Fiddle here.

Note:

Name of class never starts with numeric values.

Upvotes: 0

Aamir Afridi
Aamir Afridi

Reputation: 6411

$(function(){
    //$('.div1').append('(', $('.div2'), ')'); //this is better way but you can try following
    $('.div1').append($('.div2'));
    $('.div2').html('('+$('.div2').html()+')');
});

Demo: http://jsfiddle.net/aamir/jNU4B/

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

The problem is your selectors: .div1 and .div2, these are searching for elements that have the class of div1 and div2; whereas you want the div elements, with class 1 or 2.

Therefore I'd suggest:

$('div.2').text(function(i,t){
    return '(' + t + ')';
});
$('div.1').append($('div.2'));

JS Fiddle demo.

Although do be aware that using a numeral character as the first character of a class, or id, can be problematic in CSS.

References:

Upvotes: 1

Related Questions