0

Here is jsfiddle link - http://jsfiddle.net/howg59sg/5/

<div id='test1'>
    <ul>
        <li id="li1" friendName="foo">test 1</li>
        <li id="li2" friendName="bar">test 2</li>
    </ul>
</div>

function myclick() {
    alert("clicked");
    var elemId = "#li1";
    var elemCollection = jQuery(elemId);
    alert("len = " + elemCollection.length);
    if (elemCollection.length) {
        var selectedElem = elemCollection[0];
        alert("id of the element to work on " + selectedElem.attributes["id"].value);
        var stringToReplaceWith = "testing";
        alert("friendname = " + selectedElem.attributes["friendname"].value);
        //alert("html value of selected elem = " + selectedElem.html());

        selectedElem.html(stringToReplaceWith);
    } else {
        alert("none");
    }

}

As you can see, I am trying to update the html content of a li element using jQuery. This results in following error:

Uncaught TypeError: undefined is not a function

I am able to get attributes on this li element but html() setter fails. Even getter fails as well which i have commented out in the code for now...

Does anyone know, What might be wrong here?

Thanks for the help.

1
  • I suggest using console.log() instead of alert(), it's much easier to deal with. Commented Feb 1, 2015 at 1:28

3 Answers 3

1

You get the error because selectedElem is not a jQuery object.

var selectedElem = elemCollection[0];  <-- gets the DOM node
selectedElem.html(stringToReplaceWith);  <-- you treat it as a jQuery object

either use .eq(0) to get the element as jQuery instead of bracket notation and use .attr() to read the attributes Or wrap it with jQuery() or use innerHTML

Sign up to request clarification or add additional context in comments.

1 Comment

That solved the problem. I didn't know that distinction. Thanks for pointing it out.
1

Your issue is likely with this line:

var selectedElem = elemCollection[0];

That will give you a regular DOM element object instead of a jQuery object. DOM elements don't have the html() function like jQuery objects do. You can replace the whole function with just these lines of code:

function myclick(){
  jQuery('#li1').html('testing');
}

1 Comment

yeah, i didn't know that difference. Thanks. I can't though do what you suggest because in my app, it is possible that this element may not be present on the page. (it will be there on only one page). So I have to check the collection length. But again, now the issue is resolved.
1

The following line returns a native DOM Html element:

elemCollection[0];

If you want the first item in a collection as a jQuery element use first():

elemCollection.first();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.