简体   繁体   中英

Jquery removing <p> tag from success fn

I get response in my ajax success fn. My data variable gives me <p>hello</p> .

How do I remove <p> and </p> from my data variable ?

I used .remove() but it is not working.

Try this:

var data = '<p>hello</p>'
var text = $(data).text();
console.log(text);

.remove() removes elements from the DOM, not from strings.

If you want to delete the <p> you can add the results to the DOM as hidden then remove the <p> and only then show it.

You can also try this example . There will be no need to remove P tags.

var content = $(ajaxResponseString); //content = $("<p>Data</p>");
var html = content.html();

Advantages of this method:-

  • Its more simple than using regular expressions.
  • If your response comes as <p id='paraId'> data </p> . It will still run.
  • Take this case <p > data </p> , this approach will run fine while regex may/may not depending upon how clean your regex is.
  • If your response changes tomorrow and you expect any other HTML tag too then you need to update your regex which can be quite complex to handle.

Try this out:- http://jsfiddle.net/adiioo7/b5bG8/

JS:-

var html = "<p>Some HTML</p>";
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
alert(text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM