user3743128
user3743128

Reputation: 65

How to apply a class attribute to an HTML string (not rendered on the document)

I am am developing code for am automator to improve the project with several pages.

I have a textarea input where I can enter HTML and it shows me the HTML with the right structure.

HTML:

<textarea name="message">
<input type="text" value="TextTwo" id="texttwo"/>
<input type="text" value="DataOne" id="dataone"/>
<input type="text" value="NumberTwo" id="numbertwo"/>
<input type="text" value="TextOne" id="textone"/>
<input type="text" value="DataTwo" id="datatwo"/>
<input type="text" value="NumberOne" id="numberone"/>
</textarea>

<button>process</button>

JS/JQuery:

$('button').click(function () {
    var code = $('textarea[name=message]').val();

    if ($('#output').length < 1) {
        $("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
    }        



    $('#output').val(code);
});

I would like to apply classes following these rules:

An example of how the code would output in textarea

<input type="text" value="TextTwo" id="texttwo" class="text" />
<input type="text" value="DataOne" id="dataone" class="data" />
<input type="text" value="NumberTwo" id="numbertwo" class="number" />
<input type="text" value="TextOne" id="textone" class="text"/>
<input type="text" value="DataTwo" id="datatwo" class="data" />
<input type="text" value="NumberOne" id="numberone" class="number" />

DEMO CODE

What is a good approach to do this using JQuery?

Upvotes: 0

Views: 223

Answers (5)

Maulik Anand
Maulik Anand

Reputation: 1449

DEMO

$('button').click(function () {
    var code = $.parseHTML($('textarea[name=message]').val());
    console.log(code);
    var newCode = "";

    code = $.grep(code, function (n, i) {
        if (n.nodeValue) {
            return n.nodeValue.trim()
        } else {
            return (n.outerHTML && n.outerHTML.trim())
        }
    });

    for (var i = 0; i < code.length; i++) {
        var element=$(code[i]);
        element.addClass(element.attr("type"));
        newCode += code[i].outerHTML;
    }
    console.log(newCode);
    console.log(code);


    if (!$('#output').length) {
        $("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
    }




    $('#output').val(newCode);
});

Upvotes: 1

Adam Merrifield
Adam Merrifield

Reputation: 10407

Under the assumption that all the html in the textarea is valid, What we can do is just build the html into a div and then format the html with jQuery. After this is done just get the content and put it in the textarea.

$('button').click(function () {
    var code = $('textarea[name=message]').val(),
        $code = $('<div />').html(code),
        classes = {'Text': 'text', 'Data': 'data', 'Number': 'number'};

    if ($('#output').length < 1) {
        $("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
    }

    $('input', $code).each(function(){
        var t = this,
            $t = $(this);

        for(key in classes){
            if(t.value.indexOf(key) > -1){
                $t.addClass(classes[key]);
                return;
            }
        }
    });

    $('#output').val($code.html());
});

http://jsfiddle.net/LC5y3/4/

Upvotes: 1

Gio
Gio

Reputation: 1

You can dynamically build the elements:

$('input').addClass('className').attr('value','number');

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

I updated your fiddle and had this code working -- Can't give you a link since I don't actually have a fiddle account:

$('button').click(function () {
    var code = $('textarea[name=message]').val();

    // The best thing to do here is to turn that string of HTML into
    // DOM elements and let the browser do the work.

    var elms = jQuery.parseHTML(code);
    var result = "";

    // Now that we've processed the HTML into an array, work with it.
    for (var i = 0; i < elms.length; i++) {
        var el = elms[i];
        if (el.tagName && el.tagName.toLowerCase() === "input") {
            // Great! We we have an 'input' element.
            var val = el.value;

            if (val.indexOf("Text") !== -1) {
                el.className = "text";
            }
            if (val.indexOf("Data") !== -1) {
                el.className = "data";
            }
            if (val.indexOf("Number") !== -1) {
                el.className = "number";
            }            
        }

        if (el.nodeType === 3) {
            // Handle text nodes
            result += el.nodeValue;
        } else {
          result += el.outerHTML;
        }        
    }


    if ($('#output').length < 1) {
        $("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
    }        



    $('#output').val(result);
});

Upvotes: 3

Praveen Reddy
Praveen Reddy

Reputation: 7383

You can use the attribute contains selector.

jsFiddle

$('input[id*="text"]').addClass('text');
$('input[id*="number"]').addClass('number');
$('input[id*="data"]').addClass('data');

Upvotes: 0

Related Questions