0

I'm dynamically constructing elements for recurring html.

I'm creating a display:table, and all seems to be going well, but when I change the name of an element before it's been $.append()ed, it doesn't show up in Chrome "Elements" and cannot be later selected by jQuery; however, before $.append()ing, the $.prop('name') can be alert()ed.

Should the dynamically constructed element be $.append()ed before changing $.prop('name')?

Code sample:

$.fn.appendSingleRecordInsert = function(paramaterObject) {
    return this.each(function () {
        var $appendDiv = $('<div/>')
        ...
        $.each(paramaterObject.rows, function(rowKey, rowValue){
            var $rowDiv = $('<div/>');
            $.each(rowValue.columns, function(columnKey, columnValue){
                var $columnDiv = $('<div/>');
                if(typeof columnValue.name !== 'undefined'{
                    $columnDiv.prop('name', columnValue.name);
                }
                ...
                $rowDiv.append($columnDiv);
            })
            $appendDiv.append($rowDiv);
        });
        $(this)[paramaterObject.domInsertMethod]($appendDiv);
    });
  • The element is visible and shows up in inspect element but just has the wrong name? Have you tried `attr` instead? – James Montagne Jun 10 '13 at 14:07
  • @JamesMontagne yep, all the rest of the code around it works as expected. thought `attr` was "bad" ;)) will try!....`UPDATE`: it worked! want to expand to answer? have any idea why? –  Jun 10 '13 at 14:08
  • In my head at least, `attr` makes more sense when working with an element which has not been added to the dom. – James Montagne Jun 10 '13 at 14:10
  • @JamesMontagne i def learned something new today, ty! do you mind expanding to answer for later readers? –  Jun 10 '13 at 14:16
  • 1
    checkign on a few things. Posted an answer, will likely update with a bit more detail. – James Montagne Jun 10 '13 at 14:18
  • 1
    When you say it "can't be selected by jQuery", do you mean you are trying to select with the attribute selector? `$("div[name=...`? – James Montagne Jun 10 '13 at 14:37
  • @JamesMontagne yep, but it can now because of your fix. i changed it to a `class` to be more correct as you and Bergi recommended –  Jun 10 '13 at 14:40

2 Answers2

2

The name property is not applicable to <div> elements - they have no name attribute. Because of that, the property change you're doing will not be reflected in the attribute values (DOM inspector).

You should use an id or a class instead if you need a selector.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

You can try attr instead of prop. The "attribute selector" selects based on attributes, not properties. In order to do something like $("div[name=... you must set the attribute, not the property.

It should be noted though that name is not a valid attribute on a div.

James Montagne
  • 77,516
  • 14
  • 110
  • 130