Skip to content Skip to sidebar Skip to footer

Create DOM Element With JQuery

I have a function $(document).ready(function () { $('#btnhighlight').click(function () { var htext = $('#txthighlighttext').val(); $('#lstCo

Solution 1:

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);
        });
    });
});

Solution 2:

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)


Solution 3:

Its quite simple

var newEl = $('<div THE_ATTRIBUTES_YOU_WANT></div>');
$('THE_ELEMENT_YOU_WANT_TO_APPEND_OR_ADD').append(newEl);

Post a Comment for "Create DOM Element With JQuery"