Upendra Sharma
Upendra Sharma

Reputation: 13

Uncaught Error: Syntax error, unrecognized expression when using replaceWith

I am using replaceWith to replace images with their source only. The code i am using is below

var html = 'Hello<div><br></div><img src="abc.png" class="img-responsive" style="width: 100%;"><div><br></div><div>Video</div><div><br></div><div><br></div><iframe src="https://www.youtube.com/embed/40pH_we3niw" class="img-responsive" style="width: 100%;"></iframe><div><br></div><div>Image</div><div><br></div><div><br></div><img src="def.png" class="img-responsive" style="width: 100%;"><div><br></div><div>video 1</div><div><br></div><div><br></div><iframe src="https://www.youtube.com/embed/LlW8tqMKEAM" class="img-responsive" style="width: 100%;"></iframe>';

var $html = $(html);

$('img', $html).replaceWith(function () {
    return $(this).attr('src');
});

html = $html.html();

console.log(html);

But this is giving error as below

Uncaught Error: Syntax error, unrecognized expression:

What is wrong with the code and how to fix this?

Upvotes: 0

Views: 1239

Answers (1)

Quentin
Quentin

Reputation: 943564

Pay attention to which line the error is reported on. This has nothing to do with replaceWith.

It errors here:

var $html = $(html);

The $ function is heavily overloaded.

It does different things depending on what you pass it.

Even if you pass it a string, it does different things depending on features of the string.

The first character in your string is an h, which is not a < so it attempts to parse it as a CSS selector and not a chunk of HTML.

You need the string to have a root element for this to work.

var html = 'Hello<div><br></div><img src="abc.png" class="img-responsive" style="width: 100%;"><div><br></div><div>Video</div><div><br></div><div><br></div><iframe src="https://www.youtube.com/embed/40pH_we3niw" class="img-responsive" style="width: 100%;"></iframe><div><br></div><div>Image</div><div><br></div><div><br></div><img src="def.png" class="img-responsive" style="width: 100%;"><div><br></div><div>video 1</div><div><br></div><div><br></div><iframe src="https://www.youtube.com/embed/LlW8tqMKEAM" class="img-responsive" style="width: 100%;"></iframe>';

var $html = $(`<div>${html}</div>`);

$('img', $html).replaceWith(function() {
  return $(this).attr('src');
});

html = $html.html();

console.log(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 4

Related Questions