简体   繁体   中英

Dynamically change a div's ID?

I have a bunch of divs with weird id and each of them contains a video. They're actually video embed codes but they're not usual to me. Here's one example:

<div id="evp-1fae4e37639894816f03591bc7009c68-wrap" class="evp-video-wrap"></div><script type="text/javascript" src="http://domain.com/evp/framework.php?div_id=evp-1fae4e37639894816f03591bc7009c68&id=cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg%3D%3D&v=1278525356"></script><script type="text/javascript">_evpInit('cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg==');</script>

What I want to do is create a video playlist. As a part of that, I created list using divs also which use the onclick attribute to trigger my JS function to switch between videos. Here's how it looks:

<div class="vid-list" onclick="switchvideo('http://domain.com/html-vids/headline-vids/second-vid.html', 2)"><p>This a video tutorial for blah blah blah.</p></div>

The problem is, each time I switch to another video the div id of the embed code changes also because otherwise it won't work. So I need to change that before loading the video script inside the div. I tried to achieve that using the following JS function:

function switchvideo(url, vidnumber)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  xmlhttp.open("GET",url,false);
  xmlhttp.send(null);
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.open("GET",url,false);
  xmlhttp.send();
  }

var div_node = document.getElementByClass('evp-video-wrap');

if ( vidnumber == 2 ) {
    div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
   }
document.getElementById(div_node.id).innerHTML=xmlhttp.responseText;
}

Apparently it's not working. I suspect the problem are the lines in bold above. I tried to get the element by 'class' and its id by using 'div_node.id'. I am assuming that by doing 'document.getElementByClass', I am getting the reference to that element so I could use it to manipulate its other attributes. But I am not sure... Could anyone pls enlighten me??

There is no getElementByClass() method. There is a getElementByClassName() but it's not available in every browser.

Here is one you can use:

// http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(searchClass, node, tag) {
  var classElements = new Array();
  if (node == null) node = document;
  if (tag == null) tag = '*';
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
  for (i = 0, j = 0; i < elsLen; i++) {
    if (pattern.test(els[i].className)) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

Then you can call it as

getElementByClass('evp-video-wrap');

Your ajax is a bit tricky, but here is a more general one:

function getXmlHttpObject() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!xmlHttp) {
        alert("Your browser does not support AJAX!");
    }
    return xmlHttp;
}


function ajax(url, onSuccess, onError) {

    var xmlHttp = getXmlHttpObject();

    xmlHttp.onreadystatechange = function() {
        if (this.readyState === 4) {

            // onSuccess
            if (this.status === 200 && typeof onSuccess == 'function') {
                onSuccess(this.responseText);
            }

            // onError
            else if(typeof onError == 'function') {
                onError();
            }
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return xmlHttp;
}

Finally your code becomes:

function switchvideo(url, vidnumber) {
  var div_node = getElementByClass('evp-video-wrap')[0];

  // make a call to the url, and execute the
  // callback when the response is available
  ajax(url, function( responseText  ){
    if (vidnumber == 2) { 
      div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap'; 
    }
    document.getElementById(div_node.id).innerHTML = responseText;      
  });
}​

You can see the whole code [ here ]

getElementByClass isn't a standard method. Is it possible for you to use a framework for this? jQuery has a nice mechanism to search for an element by class, as do the other frameworks. It also makes it much easier to do the AJAX bits in a cross-browser supported way.

function switchvideo(url, vidnumber) 
{ 
     $.get(url, function(data) { 
          var div_node = $('.evp-video-wrap');
          if (vidnumber == 2) {
             div_node.attr('id', 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap');
          }
          div_node.html( data ); 
     });
}

An alternative would be to write your own getElementByClass or specific code to search for a DIV by class. Note: I assume you're only interested in the first match.

function getDivByClass( klass )
{
    var regex = new RegExp( '(^|\\s+)' + klass + '(\\s+|$)' );
    for (div in document.getElementsByTagName('div')) {
        if (regex.text( div.className)) {
            return div;
        }
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM