tags:

views:

119

answers:

5

How can I dynamically name id's using javascript?

Something like this:

js:

var idName = "fruit";

html:

<img id="javascript:idName" src="banana.jpg">
+1  A: 
var bananaImage = new Image();
bananaImage.id = "fruit";
bananaImage.src = "banana.jpg";
Kevin Crowell
A: 

You can dynamically create elements, such as <img>, and set their attributes using JavaScript's DOM API.

middus
+1  A: 

Using the jQuery framework you could do something like:

<img class="idName" src="banana.jpg"/>
<img class="idName" src="cherry.jpg"/>

The script ...

var idName = 'fruit';

$(function() {
    $('img.idName').each(function(i) {
        $(this).attr({id: idName+i});
    });
});

... which results in:

<img id="fruit0" class="idName" src="banana.jpg"/>
<img id="fruit1" class="idName" src="cherry.jpg"/>
aefxx
A: 

or you can get the element any other way IE

imgs = container.getElementsByTagName("img");
foreach(imgs as img){
    if(imgs.src == "banana.jpg") img.id = "fruit";
}

Note: foreach doesn't work in JS you'll need a for loop, but I'm too lazy :P

Javier Parra
A: 

I think this is what your looking for. You need some sort of event to trigger the JavaScript. Since IMG doesnt have it, except for user events, you need something like:

<head>
<script language="JavaScript" type="text/javascript">
function nameMyIds() {
   var idToName = "firstImageId";
   var theImage = getImageBySrc("banana.jpg");
   if (theImage!=null)
       theImage.id = idToName;
}
function getImageBySrc(src) {
    // using DOM, using jQuery would make this easier
    var allImages = document.body.getElementsByTagName("IMG");
    for (var i=0; i<allImages.length; i++ ) {
        var img = allImages[i];
        var i = img.src.indexOf(src);
        if (img.src == src || img.src.indexOf(src) > 0) { return img };
    }
}
</script>
</head>
<body onload="nameMyIds()">
    <img src="banana.jpg">
</body>
Jason Jong