Atma
Atma

Reputation: 29767

how to get and modify a specific element from an already retrieved jquery object?

I have the following html string that I want to convert:

<ul class="errorlist"><li>myfield<ul class="errorlist"><li>My Error.</li></ul></li></ul>

I believe I convert the html to a jquery object like this:

errorUL = $(<ul class="errorlist"><li>myfield<ul class="errorlist"><li>My Error.</li></ul></li></ul>)

I want to add an id to the first UL. How do I get this element and add an id to it?

Upvotes: 0

Views: 50

Answers (3)

Shailesh Rathod
Shailesh Rathod

Reputation: 106

$("ul:first").attr({id:"your id"});

The above code help you, to get the first ul element and specify the id on it.

Upvotes: 0

Leonardo Gonzalez
Leonardo Gonzalez

Reputation: 1529

If you just need to add an id to the first ul in your markup, you don't need to "convert the HTML to a jQuery object" -- you can just use jQuery selectors to create a jQuery object with which you can manipulate the original DOM object

With this in your HTML markup:

<ul class="errorlist"><li>myfield<ul class="errorlist"><li>My Error.</li></ul></li></ul>

You would simply need this JS:

$('ul.errorlist').first().attr('id', 'theID');

The 'ul.errorlist' selector matches all ul tags with the errorlist class, and returns a jQuery collection with objects for both DOM elements. The first() function returns the first object in the matching collection, to which you can chain the attr() function to set the value of the id attribute (in the above example, setting it to "theID").

Upvotes: 0

Neil S
Neil S

Reputation: 2304

using chaining:

var $ul = $('<ul class="errorlist"><li>myfield<ul class="errorlist"><li>My Error.</li></ul></li></ul>')
.attr('id','newID');

make sure you wrap strings in quotes when you pass them to the jQuery object ($)

Upvotes: 1

Related Questions