find first occurrence of class in div

前端 未结 8 2335
傲寒
傲寒 2020-12-14 05:45

I have the below html structure, i want to find the inner html of first div with class as \"popcontent\" using jQuery

8条回答
  •  时光取名叫无心
    2020-12-14 06:01

    You could use document.querySelector()

    Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.

    Since it is only looking for first occurence, it has better performance than jQuery

    var count = 1000;
    var element = $("").addClass("testCase").text("Test");
    var container = $(".container");
    var test = null;
    for(var i = 0; i < count; i++) {
    	container.append(element.clone(true));
    }
    
    console.time('get(0)');
    test = $(".testCase").eq(0);
    console.timeEnd('get(0)');
    console.log(test.length);
    
    console.time('.testCase:first');
    test = $(".testCase:first");
    console.timeEnd('.testCase:first');
    console.log(test.length);
    
    console.time('querySelector');
    test = document.querySelector(".testCase");
    console.timeEnd('querySelector');
    console.log(test);
    
    

    jsFiddle version of snippet

提交回复
热议问题