TERACytE
TERACytE

Reputation: 7863

Processing groups of HTML elements using jQuery/Javascript?

I have an HTML 5 page with several articles. Each article has a custom attribute titled "MyAttribute":

<html>
    <article MyAttribute="x">
    <article MyAttribute="y">
    <article MyAttribute="z">
</html>

I would like to create a function that does something like the following pseudo-code:

for each article {
    get MyAttribute from the article
    if MyAttribute == x {do this}
    if MyAttribute == y {do that}
    if MyAttribute == z {do something else}
}

What is the most efficient way to do this using jQuery/JavaScript?

Upvotes: 1

Views: 167

Answers (3)

nikmd23
nikmd23

Reputation: 9103

Instead of using custom attributes, I'd recommend placing your "MyAttribute" in a data-* attribute like this:

<html>
  <body>
    <article data-myattribute="x"></article>
    <article data-myattribute="y"></article>
    <article data-myattribute="z"></article>
  </body>
</html>

This creates "more valid" HTML. Then you would write javascript like this:

$('article').each(function (){
    switch ($(this).data('myattribute')){
        case 'x':
            //do something for x
            alert('this is case X');
            break;
        case 'y':
            //do something for y
            alert('this is case Y');
            break;
        case 'z':
            //do something for z
            alert('this is case Z');
            break;
    }
 });

I've also created a jsFiddle of the result for you.

Upvotes: 2

Marco Johannesen
Marco Johannesen

Reputation: 13134

f you insert these attributes server-side, the page will not validate and might trigger quirks mode in the browser.

You could do data-myattribute and then use data().

$('article').each(function() {

    var MyAttribute = $(this).attr('data-myattribute');

    if (MyAttribute == 'x')
        //code
    else if (MyAttribute == 'y')
        //code
    else if (MyAttribute == 'z')
        //code
});

Upvotes: 1

Ben
Ben

Reputation: 10104

$('article').each(function() {
    if (this.MyAttribute == 'x')
        //...
    else if (this.MyAttribute == 'y')
        //...
    else if (this.MyAttribute == 'z')
        //...
    //etc.
});

Upvotes: 1

Related Questions