Possible Duplicate:
How to get elements with multiple classes
Working on a bit of javascript code that sets the current URL of the referring page to pass into an iframe widget. No control over the code of the page on which the javascript resides, except for the one bit of javascript code.
An example of the element value I need to grab is as follows:
<div id="new_p_2FRolls-Royce_p_2F2013-Rolls-Royce-Phantom_p_2BDrophead_p_2BCoupe-4a5be12c0a0a00650143b598a45df25d_p_2Ehtm" class="page NEW_VEHICLE_DETAILS current">
What I'm trying to do is select the div by combining classes "page" and "current". In this example, "NEW_VEHICLE_DETAILS" is unique to this page, and varies on other pages. I would like to create a consistent bit of code that doesn't have to be altered for each page as it is currently. Here is the code I am using right now:
<div id="build_iframe"></div>
<script>
var pageid = document.getElementsByClassName('NEW_VEHICLE_DETAILS')[0].id;
var currenturl = 'http://m.whateverwebsite.com/index.htm#'+pageid;
var shareurl = escape(currenturl);
document.getElementById('build_iframe').innerHTML = '<iframe style="border:1px;width:100%;height:110px;" src="http://widget.mywidgetwebsite.com/share-tool/?current_url='+shareurl+'"></iframe>';
</script>
jQuery is not an option in this case. How can I get the value of the ID by selecting only the element with BOTH "page" and "current" classes set?
HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.
Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names. Here is the HTML for the examples in this article.
Attribute Values Specifies one or more class names for an element. To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.
You could use querySelector
(or querySelectorAll
if there's more than one matching element and you want to get a reference to all of them):
var elem = document.querySelector(".page.current");
You can also actually just use getElementsByClassName
, which accepts a space-separated list of class names:
var elems = document.getElementsByClassName("page current");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With