1

I am checking for html elements in a string. This works but I have a ton of html elements to check and for various strings. Can this be simplified so I can check all common html element types?

    $("<div/>").html(test_string).find('a').each(function (idx, elm) {
        //here are your anchors
        test_string = "error saving test string. can't contain html elements.";
    });

    $("<div/>").html(test_string).find('img').each(function (idx, elm) {
        test_string = "error saving test string. can't contain html elements.";
    });

    $("<div/>").html(test_string).find('input').each(function (idx, elm) {
        test_string = "error saving test string. can't contain html elements.";
    });

2 Answers 2

2

Create just one element, populate its HTML, and then use the selector string a, img, input, and check the .length of the resulting collection:

let test_string = 'foo <input> bar';

const $div = $("<div/>").html(test_string);
if ($div.find('a, img, input').length) {
    test_string = "error saving test string. can't contain html elements.";
    console.log("error saving test string. can't contain html elements.");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Comments

1

You can create div and add string to it and just check if it contains any child element, this way you don't need to put check of every type of html tags / element

var $div = $("<div/>").html(test_string);
if($div.children().length>0) {
        //here are your anchors
        test_string = "error saving test string. can't contain html elements.";
  );

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.