-1

Is it possible to use $(someSelector).html('some string'); and not replace the content of this selector but add the 'some string' at the beginning of the content?

Also after I add it is it possible to remove the 'some string' from the "someSelector" html?

7 Answers 7

4

Q #1: jQuery.prepend() accepts an HTML string.

Q #2: Yes. One possible option is by using the native .replace() method.

Sign up to request clarification or add additional context in comments.

4 Comments

Any idea why I wouldn't have replace method?
It's a native JS method (not jQuery). See here. It must be called on a string. I'm betting you are trying to do $(someSelector).replace()?
so something like this should work? var html = $('.items-large').html(); html.toString().replace("<div class='width-specifier-large'><img src=" + url + " alt='@Model.ProductName'/> onerror='onImgErrorSmall(this)'</div> ", ''); and then $('.items-large').html("<div class='width-specifier-large'><img src=" + url + " alt='@Model.ProductName'/> onerror='onImgErrorSmall(this)'</div> " + html);
Please post a link to a pastebin of that. Comments are not good for large blocks of code.
2

Use .prepend() -> http://api.jquery.com/prepend/

Comments

1

You could either get the current HTML of the element, prepend the string, and then change the HTML, or you could use .prepend().

$("#me").prepend("Some string.");

Comments

1

to add:

$(someSelector).prepend('foo');

to remove:

$(someSelector).html($(someSelector).html().replace('foo',''));

Comments

1

Perhaps prepend [ http://api.jquery.com/prepend/ ] with an element (span for example)

$(someSelector).prepend('<span id="somethingunique">some string</span>');

So you could remove later

$("#somethingunique").remove();

Will this work for you?

1 Comment

I have to remove some html from a class. This will not work, but thanks
1

Yes you can use .prepend('some string').

Which 'some string' do you want to then remove?

1 Comment

good point, I guess first I should remove it, and then I should prepend the html.
0

Do you mean something like this:

var content = $(someSelector).html(); 
var newContent = 'some string' + content;
$(someSelector).html(newContent);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.