jacktrades
jacktrades

Reputation: 7392

Modify a paragraph element inside a div

Need to add an element in a web page, cloning the actual.

console.log(($this)); 

Gives something like this:

<div id="id" class="class" style="style">
<p style="style">World</p>
</div>

I want to add word "Hello" with the exact same structure, before "World"

Tried with attr() or html() but replaces all the attributes.

Upvotes: 0

Views: 1724

Answers (5)

lbstr
lbstr

Reputation: 2832

You mention that you want to "clone the actual". Here's how you would clone $this and modify the clone's contents:

var $clone = $this.clone();
$clone.find('p').text(function(i, oldText){
    return "Hello " + oldText;
});
$clone.appendTo('#someContainer'); // now put the copy somewhere else

EDIT: Keep in mind when cloning that you don't want to have multiple elements with the same id. It looks like you just put id="id" in there for the sake of example, but its still worth pointing out.

Upvotes: 1

Aliaksandr Kazlou
Aliaksandr Kazlou

Reputation: 3301

var $hello = $(("#id > p")).clone();
$hello.text("Hello");
$hello.prependTo($("#id"));

http://jsfiddle.net/VmAPr/

Of course, you can use :first or :first-child selectors if necessary and assign intermediate results into the variable or to everything in one line )

Upvotes: 1

11684
11684

Reputation: 7507

One-liners ftw:

$("#id > p").prepend("Hello ");

Upvotes: 2

Engineer
Engineer

Reputation: 48793

$('#id > p').text(function(i,oldValue){
    return "Hello " + oldValue;
});

Upvotes: 1

Shyju
Shyju

Reputation: 218722

var currentcontent=$("#id").find("p").text();
$("#id").find("p").text("Hello"+currentcontent);

This will do it for only one DIV with that particular ID (Id]s are unique)

Sample : http://jsfiddle.net/trdxg/2/

If you want to do it for n number of elements with same structure, you can change your jQuery selector to use the class.

$(function(){
    $("div.class").each(function(index,item){
       var item=$(this);
        var currentcontent=item.find("p").text();
        item.find("p").text("Hello"+currentcontent); 

    }); 
});​

Sample : http://jsfiddle.net/trdxg/7/

Upvotes: 1

Related Questions