Friday, May 10, 2024
70
rated 0 times [  75] [ 5]  / answers: 1 / hits: 28551  / 12 Years ago, sun, may 20, 2012, 12:00:00

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

More From » getelementbyid

 Answers
41

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();

[#85467] Friday, May 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aliah

Total Points: 118
Total Questions: 132
Total Answers: 94

Location: Tajikistan
Member since Fri, Sep 11, 2020
4 Years ago
;