Home > OS >  Why does jquery recognizes an element stored as a string in a variable when using .prop(), but not w
Why does jquery recognizes an element stored as a string in a variable when using .prop(), but not w

Time:06-27

I stored an Id of a in a variable,variantId = $(this).prop('id') and noticed 2 different behaviors of Jquery: When I changed the prop of the <td> - jquery recognized the element stored in the variable although it was stored as a string,

let variantId;
$(document).on('click', ".tbl-itemClass", function () {
    variantId = $(this).prop('id');
    $(variantId).prop('contenteditable', true);//changed the prop

}).

but when I tried getting the value of the <span> nested in the <td>, using .text(), jquery only recognized the element stored in the variable when '#' was added

    on('input', function () {
            let newItemName = $('#'   variantId).find('span.item-description').text();
            //let newItemName = $(variantId).find('span.item-description').text(); //this line returned an empty string instead of the <span>s value.
        })

this is the full code:

let variantId;
        $(document).on('click', ".tbl-itemClass", function () {
            variantId = $(this).prop('id');
            $(variantId).prop('contenteditable', true);

        }).
            on('input', function () {
                let newItemName = $('#'   variantId).find('span.item-description').text();
                //let newItemName = $(variantId).find('span.item-description').text();
            });

This is my .csHtml (don't think it makes a difference, I'm using razor page, Asp.Net)

<tbody>
@foreach (var item in Model)
{
    <tr currentitemid=" @item.Id">
        <td  id="@("description"  item.Id)" varianttype="@ViewBag.VariantType" >
            <span >&nbsp;&nbsp;&nbsp;</span>
            <span style="width:90%; padding:1px 5px 1px 2px;" **** contenteditable> @item.Description </span>
        </td>
        
        <td >//more code here
        </td>
    </tr>
}

Can you explain the difference please? Thanks!

CodePudding user response:

In jQuery, if you want to select attribute by ID you need to put:

$('#yourId')...

As you are getting variantId stored and used as id, to access elements .text() you need # as id selector.

CodePudding user response:

The answer to this question is that this line

    $(variantId).prop('contenteditable', true);//changed the prop

did NOT work, and the reason why you can mistaken and think it works is because it has the contenteditable attribute in the html element.

  • Related