Jquery selector contains single text

I need help for one thing:

this is my jQuery idea:

        var text = "Some Text1, Some Text2, Some Text3";


        $("h3:contains('"+even one of  this string+"')").each(function() {
                $(this).append("<span>Some Text</span>");
        });

This is my HTML.

            <h3 class="test1">Some Text2</h3>

            <h3 class="test1">Some Text1</h3>

            <h3 class="test3">Another Text</h3>

What I want in OUTPUT:

             <h3 class="test1">
                 Some Text2
                <span>Some Text</span>
            </h3>

            <h3 class="test1">
                Some Text1
                <span>Some Text</span>
            </h3>

            <h3 class="test3">Another Text</h3>

Thank!

+3
source share
5 answers

fast jQuery

var text = "Some Text1, Some Text2, Some Text3";

$(document).ready(function(){
  $(text.split(", ")).each(function(i,v){
    $('h3:contains("'+ v +'")').append('<span>Some text</span>');
  })
})

quick demonstration

+4
source
var text = "Some Text1, Some Text2, Some Text3";

var aText = text.split(","); //splits into array on comma delimiter


for (var i = 0; i < aText.length; i++) {
    $("h3:contains('" + aText[i] + "')").each(function() {
        $(this).append("<span>Some Text</span>");
    });

}

This should work for you (but it is not clear if you can break / exclude the selector line. Let me know if this is good.

+3
source

$(this).text(). , :

$.extend($.expr[':'], {
  matches: function(node, index, args, stack) {
    var re = new RegExp(args[3]);
    return !!$(node).text().match(re);
  }
});

$(function() {
  $('h3:matches("Some Text[123]")').each(function() {
    $(this).append("<span>Some Text</span>");
  });
});
+3

:

$("h3:contains('Some Text1'), h3:contains('Some Text2'), h3:contains('Some Text3')").each(function() {
            $(this).append("<span>Some Text</span>");
    });

OP , :

var text = "Some Text1, Some Text2, Some Text3";

text.replace(/\s?([^,]+?)(,)|\s([^,]+?)$/g, "h3:contains('$1$3')$2");

.

:

var text = "Some Text1, Some Text2, Some Text3";

text.replace(/\s?([^,]+?)(,)|\s([^,]+?)$/g, "h3:contains('$1$3')$2");

$(text).each(function() {
            $(this).append("<span>Some Text</span>");
    });

This will replace all terms separated by commas with the term itself surrounded by h3: contains ('and'). They will be separated by commas just like the original line.

+1
source

A simple solution if you know that your strings ahead of time will use multiple selectors, for example:

$("h3:contains('Some Text1'), h3:contains('Some Text2'), h3:contains('Some Text3')").each(function() {
    $(this).append("<span>Some Text</span>");
});
0
source

Source: https://habr.com/ru/post/1744260/


All Articles