javascript变量中的javascript getElementsByClassName [英] javascript getElementsByClassName from javascript variable
问题描述
我从有角度的get请求中获取了一些html,并且试图从此响应中获取一些特定的元素.这是带有"post-holder"类的div的列表.提取html效果很好,但是要提取每个div分别插入会有一些麻烦.
I'm getting some html from a angular get request and I'm trying to get some specific elements from this response. Which is a list of div's with the class "post-holder". Extracting the html works fine, but to extract each div to insert separately has some troubles.
这是我尝试使用的代码:
This is the code I'm trying with:
var firstTag = '<main id="posts">';
var res = data.substring(data.indexOf(firstTag) + firstTag.length, data.indexOf('</main>'));
var html2 = $.parseHTML( res );
var x = html2.getElementsByClassName("post-holder");
最后一行在chrome中给我以下错误:"TypeError:未定义不是函数".
The last line gives me the following error in chrome: "TypeError: undefined is not a function".
我猜想 getElementsByClass 对于jquery生成的变量有一些麻烦.是否有另一种方法可以做同样的事情或一种方法来解决我已经拥有的东西?
I'm guessing that getElementsByClass has some troubles with the variable generated by jquery. Is there another approach to do the same or a way to fix what I already have?
推荐答案
请参见 parseHTML的文档:
返回:数组
Returns: Array
说明:将字符串解析为DOM节点数组.
Description: Parses a string into an array of DOM nodes.
getElementsByClassName
是DOM元素上的方法,而不是数组上的方法.您需要遍历数组,检查每个值是否是一个元素(例如,相对于文本节点或注释),然后对这些值调用getElementsByClassName
.
getElementsByClassName
is a method on DOM elements, not on arrays. You need to loop over the array, check if each value is an element (as opposed to, for instance, a text node or a comment) and then call getElementsByClassName
on the values.
或者您可以只构造一个jQuery对象并在其上使用.find()
.
Or you could just construct a jQuery object and use .find()
on it instead.
这篇关于javascript变量中的javascript getElementsByClassName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!