fish man
fish man

Reputation: 2710

jquery word warp and remove wrap not worked

Some words pass from search, I want to wrap them with a div then click one link, remove the outer wrap, but my code not worked for wrap and unwrap. What is wrong?

<?php $_GET['search']='this is a text'; ?>
<script type="text/javascript" src="../jquery.js" ></script> 
<script>
    $(document).ready(function() {
        var words = '<?php echo $_GET['search']; ?>';
        $(words).wrap('<div id="words" />');
        $('body').append(words);
        $('#click').click(function(){
            $(words).unwrap('<div id="words" />');
        });
    });
</script>
<body>
    <a id="click">remove me</a>
</body>

Upvotes: 2

Views: 676

Answers (5)

akoptsov
akoptsov

Reputation: 101

Point 1 - you can wrap only DOM element, as stated above

Point 2 - before you wrap, you have to add it to the DOM, otherwise there'll be no access to added 'div'

Point 3 - if you write $(words) and $(words) two times, these are not the same object!

You should do something like:

$(document).ready(function() {
    var words = $('<span></span>').text('words words words');
    words.wrap('<div id="words"></div>');
    $('body').append(words);
    $('#click').click(function(){
         words.unwrap('<div id="words" />');
    });
});

Also check this link to jsFiddle

Upvotes: 2

Guffa
Guffa

Reputation: 700442

It's your selector that doesn't work. You end up doing $('this is a text'), which will search for a text element in a structure like this:

<this>
  <is>
    <a>
      <text></text>
    </a>
  </is>
</this>

Of course there are no such elements, so the result is an empty jQuery object.

If you want to wrap words in a text, you would have to loop through all relevant elements on the page, get their content using .text() or .html(), find words in the text and replace them with the HTML code that wraps the words, and put the text back in the elements.

Generally this is easier and more robust to do in the server side code.

Upvotes: 0

AlexBay
AlexBay

Reputation: 1313

You wrap the elements before adding them to the document and words must be a DOM element.

You might try to use $('body').append() on <div id="words">your_php_result</div> directly.

Upvotes: 0

jeffreydev
jeffreydev

Reputation: 1722

words can't be a string wrap only works on a jquery object, or a dom element.

try something like this:

<script>
$(document).ready(function() {
    var words = 'this is your search string';
    words = '<div id="words">'+words+'</div>'; // wrap it, basically creating the string
    $('body').append(words);
    $('#click').click(function(){
        $('#words').replaceWith($('#words').get(0).childNodes); // get the words outsde of it again, unwrap only works on the inner element.
    });
});
</script>
<body>
    <a id="click">remove me</a>
</body>

Upvotes: 2

cetver
cetver

Reputation: 11829

words must be selector, not a string

Upvotes: 0

Related Questions