Hello. I have a function that highlights text from a list, based on the word(s) the user is searching for. The problem is that when they write two words, for example "Juan Carlos", I want all Juan and Carlos in the list to change color. In this case it works fine. But if I search for "John id", I want to highlight the id of the span that was inserted earlier and the html breaks. How can I identify if the word is part of the attributes of a tag? or if it is contained between <>. Try to put in the text "CARLOS", "JUAN", "ID". And then try "CARLOS ID"
Thank you very much
function resaltar(control, txtResaltar) {
var str = $("#resultado").text().trim();
var textBusq = $("#textoBuscar").val();
if (textBusq == null || textBusq == "")
if (txtResaltar != null && txtResaltar != "")
textBusq = txtResaltar;
else {
return str;
}
var element = textBusq.split(' ');
$.each(element, function(index, contenido) {
var regEx = new RegExp(contenido, "gi");
str = str.replace(regEx, function(a, b) {
return '<span id="span2" style="font-weight:bold;color:red">' + a + '</span>';
});
});
$("#resultado").html(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input type="text" id="textoBuscar">
<input type="button" onclick="resaltar()" value="Buscar" />
<span id="resultado">JUAN CARLOS ID</span>
I changed the highlight function a bit, the idea now is that I evaluate all the possible searches in the same regular expression so that I don't evaluate the HTML that you add in the other iterations