I have a function
$(document).ready(function () {
$("#btnhighlight").click(function () {
var htext = $("#txthighlighttext").val();
$("#lstCodelist option").each(function () {
var sp = $(this).text();
var sp1 = sp.split(' ');
$.each(sp1, function (i, l) {
if (l == htext) {
var boldText = "<div style=\"background-color: yellow; display: inline; font-w开发者_开发知识库eight: bold;\">" + htext + "</div>";
$(document).append(boldText);
}
});
});
});
});
I updated the code but no luck. Here in this code I need to create a l has a DOM element to apply color yellow to that.
please can any body help me out how to create a dom element.
Thanks
I didn't understand where does l
is in your current code. Anyway, you can create a DOM element with jQuery like this: var myel = $('<div class="someclass"></div>')
. Then you can append myel
to wherever you want in the DOM using function like .appendTo()
, .after()
, etc.
EDIT
You seem to be trying to highlight some words inside an <option>
element. I have doubts if that is going to work on all browsers, since form elements are a little tricky when it comes to CSS. You can try something like this (untested):
$(document).ready(function () {
$("#btnhighlight").click(function () {
var htext = $("#txthighlighttext").val();
$("#lstCodelist option").each(function () {
var sp = $(this).text();
var re = new RegExp("\\b" + htext + "\\b")
sp = sp.replace(re, '<span class="highlighted">$1</span>', "gi");
$(this).html(sp);
});
});
});
You also need some CSS on your page, defining the style for .highlighted
UPDATE AFTER CHAT
I got something working using a <p>
instead of <option>
, to rule out the problem of form element styling:
http://jsfiddle.net/GTydh/3/
The updated js (in case fiddle is deleted):
$(document).ready(function () {
$("#btnhighlight").click(function () {
var htext = $("#txthighlighttext").val();
//$("#lstCodelist option").each(function () {
$("p").each(function () {
var sp = $(this).text();
var re = new RegExp("\\b(" + htext + ")\\b")
var sOpen = "<span class='highlight'>";
var sClose = "</span>";
var newhtml = sp.replace(re, sOpen + "$1" + sClose, "gi");
$(this).html(newhtml);
});
});
});
Something like this?
$(document).append($('<div />').css('color', 'yellow'));
That will append a new div with a colour of yellow to the document. If you need to add it to a specific element just use $('#myselector')
instead of $(document)
Its quite simple
var newEl = $('<div THE_ATTRIBUTES_YOU_WANT></div>');
$('THE_ELEMENT_YOU_WANT_TO_APPEND_OR_ADD').append(newEl);
精彩评论