getting first class content
i have several class with a name, how can getting content first class.
like:
<div class="hi">
<div class="hey"><input name="hello1"></div> // this is 1
<div class="hey"><input name="hello2"></div> // this is 2
<div class="hey"><input name="hello3"></div> // this is 3
</div>
only getting: class number 1 // <开发者_如何学Go;input name="hello1">
how is it with jQuery?
JSFiddle Example
// Pure JavaScript
var els = document.getElementsByClassName('hey');
els[0].innerHTML;
// jQuery
$(".hey:eq(0)").html();
$(".hey").eq(0).html();
$(".hey:first").html();
$(".hey").first().html();
$(".hey:first-child").html();
Note: In jQuery, selecting by class is usually one of the slowest methods. It's faster to select by element.className (eg div.hey
), but really, selecting by ID is the quickest (not "element#id", just "#id"). Hope this helps
If you want the html content of the first div with class 'hey', try this:
var firstChildContent = $('div.hey:first-child').html());
Try this
$('div.hey:eq(0)').html();
use the :first
selector
$('.hey:first').html(); // this is shorter (but less performant)
$('.hey').filter(':first').html(); // this is more performant (based on jQuery documentation)
or use the .first()
method
$('.hey').first().html();
or use .eq()
to get a specific index
$('.hey').eq(0).html(); // first element in the group using a 0-based index
$('.hey:eq(0)').html()
to access hello 1
similarly
$('.hey:eq(1)').html()
to access hello 2
and
$('.hey:eq(2)').html()
to access hello 3
var hey = document.getElement('.hey');
This is quite old question, but for those who find it by Google as I did: you can use document.querySelector if you do not support IE8 and lower:
var el = document.querySelector('.hey');
el.innerHTML;
Or even better you can use it on parent element:
// let's say that hi element has id instead of class
var parent = document.getElementById('hi');
var el = parent.querySelector('.hey');
el.innerHTML;
This is better than using getElementsByClassName because the browser don't need to search for all the classes in the document. So it should be also faster.
精彩评论