I need to use JavaScript to get the username which is posted in the following way:
<div id="project_user">
<p class="project_user">
by <span class="project_username"><?php echo $OwnerName; ?></span>
</p>
</div>
How do I do it?
I tried the following but it didn't work:
document.getElementById('project_username').innerHTML
You select by id
while you need to select by the className
:
document.getElementsByClassName('project_username')[0].innerHTML
Live DEMO
Note that document.getElementsByClassName
is not implemented in old IE versions...
Another way:
document.getElementById('project_user')
.getElementsByTagName('span')[0].innerHTML;
Live DEMO
You can use this "patch" to define this function in old browsers:
if (!document.getElementsByClassName) {
document.getElementsByClassName = function(classname) {
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + classname + "(\\s|$)");
for (var i = 0; i < tmp.length; i++) {
if (regex.test(tmp[i].className))
elArray.push(tmp[i]);
}
return elArray;
};
}
source
Or use a javascript library like jQuery
that implements (almost) all css selectors, example:
$('.project_username').html();
document.getElementById
only works when the element has id='targetvalue'
. Your example above shows the value being in the class
attribute, rather than the id
.
You could use getElementsByClassName
, though this isn't supported in IE8 or lower. There's also document.querySelectorAll
, which has slightly better support in IE.
You can check the browser support for various methods of getting elements online at http://www.quirksmode.org/dom/w3c_core.html#gettingelements.
Making a broad cross-browser compatible solution could be verbose:
var parent = document.getElementById("project_user"),
element;
// If the browser supports querySelectorAll, use it.
if ( parent.querySelectorAll ) {
element = parent.querySelectorAll('.project_username')[0];
// Else, if getElementsByClassName is supported, use it.
} else if ( parent.getElementsByClassName ) {
element = parent.getElementsByClassName('project_username')[0];
// Else, roll up our sleeves, let's do this the hard way
} else {
var spans = parent.getElementsByTagName("span"),
spani = spans.length;
while ( spani-- ) {
if ( spans[spani].className === "project_username" ) {
element = spans[spani];
break;
}
}
}
Or you could use something like jQuery to reduce your frustration:
var $element = $(".project_username");
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