views:

92

answers:

4

How can I get attributes values from an container using jquery ?

For example:

I have container div as:

<div id = "zone-2fPromotion-2f" class = "promotion">

here how can I get attribute id value using jquery and than how can I trim the value to get component information ?

update : how can i get attribute values ?

UPDATE: If I have multiple components on page with same div information than how would I know what attribute value is for which component ?

Thanks.

A: 

So assuming your div looks like this.

<div id="foo"/>

You could get the ID attribute by using the attr method.

$("div").attr("id);

That assumes that you only have one div on the page. Not really sure what component information you are looking to get?

ScottKoon
I have many div's on the page and so how can I get the information about it
Rachel
@Rachel I believe you need to clarify on "the information" part.
jensgram
A: 

You read node attributes with the attr() method.

var id = $( '.promotion' ).attr( 'id' );

In terms of parsing that ID for any other arbitrary information, I can't say since it looks like you're using some sort of proprietary format of which I have no knowledge.

Peter Bailey
+1  A: 

First, that seems to be a ridiculously long ID -- I'm sure it could be made much shorter while still retaining its uniqueness.

Anyway, on to the answer: First you need a way of accessing your "container" div. Typically, one might use a class or ID to get an element. For example, you could "select" this div with the following call to jQuery:

var container = jQuery('#zone-3a...'); // Fill in ... with really long ID

But, since you're asking how to retrieve the ID, I'm presuming that selecting it via the ID is not an option. You could also select it using the class, although it's not guarenteed to be the only element on the page with that class:

var container = jQuery('.promotion');

There are other ways to narrow down the search, such as:

jQuery('div.promotion');
jQuery('div.promotion:first');

Once you have a reference to your "container", you can retrieve the ID like so:

container.attr('id'); // => zone-3a...
// or:
container[0].id; // => zone-3a...
J-P
A: 

loop thru and get all divs with the class promotion and get the id of each...

$('div.promotion').each(function(){
    var attr = $(this).attr('id'); // or whatever attribute
});

or single

var myDivClass = $('zone-3a-2f-2f-2fPortal-2fPages-2fHome-2fZones-2fLeft-2f-7ccomponent-3a-2f-2f-2fSpm-2fComponents-2fPromotion-2f').attr('class');

or another single

var myDivID = $('.promotion').attr('id');
gmcalab