一般来说,我是如何从课堂上获得价值的。我的代码不起作用,我不知道为什么......
HTML
<div class="left_100_15">
Example
</div>
<p id="test">
</p>
CSS
.left_100_15{
font-size: 50px;
}
的JavaScript
var myVar = setInterval(function() { className() }, 100);
function className() {
var x = document.getElementsByTagName("*")[0].getAttribute("class");
document.getElementById("test").innerHTML = x;
}
我想要实现什么?
答案 0 :(得分:1)
如果您需要所有元素,但只获取第一个元素(不要没有原因,但是......),此代码将获取页面中的所有元素,然后获取第一个元素。
使用className
获取整个元素类。
var myVar = setInterval(function() { className() }, 1000);
function className() {
var x = document.body.children[0]; //this is returning the first of all elements that you have in your document body
var fisrtClass = x.className
document.getElementById("test").innerHTML = fisrtClass;
}
.left_100_15{
font-size: 50px;
}
<div class="left_100_15">
Example
</div>
<p class="left_100">
Example 2
</p>
<span class="left_15">
Example 3
</span>
<p id="test">
</p>
如果您出于某种原因需要编辑或获取ALL元素的值/属性,而不仅仅是第一个元素,请删除[0]
,然后您将拥有一个包含所有元素的集合,只需循环(使用for
)获得每一个。
答案 1 :(得分:1)
也许这就是你需要的,如果没有,请告诉我;)
// Be sure the code don't run before the DOM is fully loaded
window.onload = function(){
function className(){
/* This is a mistake. You are trying to get the class from the HTML tag
var x = document.getElementsByTagName("*")[0].getAttribute("class");*/
//if we log the next line in the console you will see it
console.log(document.getElementsByTagName('*')[0]);
// The best way to achieve what you want is using id's
}
className();
// Now we will go to the answer (I think you want to return the classes as an array)
function getClasses(elem){// << I'm sending the main element as a parameter
var classes = [];
for(var i=0,j=elem.children.length;i<j;i++){
classes[i] = elem.children[i].getAttribute('class');
}
return classes;
}
// Now just call the function sending the element from where you want to search classes
var abc = getClasses(document.getElementById('elem'));
var firstClass = abc[0];
document.getElementById("test").innerHTML = firstClass;
console.log(abc);
}
.left_100_15{
font-size: 50px;
}
<div id="elem" class="ola buen dia">
<div class="firstClass wuuuu juuu"></div>
<div class="firstClass testing"></div>
<div class="firstClass testClass thirdClass"></div>
</div>
<p id="test">
</p>
答案 2 :(得分:-3)
var x= parseInt(document.getElimentByClassName("name of the class").value);
我用它来了解她的价值我希望这会让你知道getelimentbyclassname是如何工作的。